Home > Net >  Why is the axios post resulting in a network error?
Why is the axios post resulting in a network error?

Time:10-15

I'm currently building an app using React Native on the frontend and Node.js together with express on the backend.

I have two axios instances, one of which I call the main server and the other the authentication server. With both instances all normal server calls outside of the following file are working expect this one. I'm currently localhosting both servers.

My frontend looks like this:

import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';

const BASE_URL = 'URL_PLACEHOLDER'; // <- IP Address of my computer

export const instanceMain = axios.create({
  baseURL: `${BASE_URL}:3000`,
  timeout: 1000,
});

export const instanceAuth = axios.create({
  baseURL: `${BASE_URL}:4000`,
});

// Interception to check if a token refresh is needed

instanceMain.interceptors.request.use(async function (response) {
  const accessToken = await AsyncStorage.getItem('accessToken');
  const refreshToken = await AsyncStorage.getItem('refreshToken');

  await instanceAuth
    .post(`/token`, {
      accessToken: accessToken,
      refreshToken: refreshToken,
    })
    .then((res) => {
      AsyncStorage.setItem('accessToken', res.data.accessToken);
      AsyncStorage.setItem('refreshToken', res.data.refreshToken);
    })
    .catch((error) => {
      console.log(error);
    });

  return response;
});

My backend of the post axios is trying to make looks like this:

app.post('/token', async (req, res) => {
  try {
    const accessToken = req.body.accessToken;
    const refreshToken = req.body.refreshToken;

    if (accessToken == null || accessToken == undefined)
      return res.sendStatus(401);

    // Verifying AccessToken
    jwt.verify(accessToken, process.env.ACCESS_TOKEN_SECRET, (error) => {
      // If it is expired this should be executed. I think I'm probably handling this
      // the wrong way, but this was the only way I could think of.
      if (error) {
        // tokenDB is an in-storage json database containing all active refresh tokens
        tokenDB.read();
        tokenDB.data ||= { tokens: [] };

        if (refreshToken == null) return res.sendStatus(401);

        // Checking if tokenDB does not contain the refresh token, if so, return 403
        if (!tokenDB.data.tokens.includes(refreshToken)) {
          return res.sendStatus(403);
        }

        // Verifying RefreshToken
        jwt.verify(
          refreshToken,
          process.env.REFRESH_TOKEN_SECRET,
          (error, account) => {
            // Deleting iat from account, otherwise the new tokens would be the same
            // as before
            delete account.iat;

            if (error) return res.sendStatus(403);

            // Generating new Tokens
            const newAccessToken = generateAccessToken(account);
            const newRefreshToken = generateRefreshToken(account);

            // Removing old refreshToken from tokenDB and push newRefreshToken to it
            tokenDB.data.tokens = tokenDB.data.tokens.filter(
              (token) => token !== refreshToken
            );
            tokenDB.data.tokens.push(newRefreshToken);

            // Result: new Access and Refresh token
            res.json({
              accessToken: newAccessToken,
              refreshToken: newRefreshToken,
            });

            tokenDB.write();
          }
        );
      } else {
        return res.sendStatus(100);
      }
    });
  } catch (error) {
    console.error(error);
  }
});

The error message simply says [AxiosError: Network Error]. error.config gives back the following, but I can't do much with it.

{"adapter": [Function xhrAdapter], "baseURL": "IP_PLACEHOLDER:4000", "data": "{\"accessToken\":\"ACCESS_TOKEN_PLACEHOLDER",\"refreshToken\":\"REFRESH_TOKEN_PLACEHOLDER"}", "env": {"Blob": [Function Blob], "FormData": [Function FormData]}, "headers": {"Accept": "application/json, text/plain, */*", "Content-Type": "application/json"}, "maxBodyLength": -1, "maxContentLength": -1, "method": "post", "timeout": 0, "transformRequest": [[Function transformRequest]], "transformResponse": [[Function transformResponse]], "transitional": {"clarifyTimeoutError": false, "forcedJSONParsing": true, "silentJSONParsing": true}, "url": "/token", "validateStatus": [Function validateStatus], "xsrfCookieName": "XSRF-TOKEN", "xsrfHeaderName": "X-XSRF-TOKEN"}

I hope I can find some help here, Thanks.

CodePudding user response:

Use redux and proper async/await function to use. Otherwise, Axios return an error. enter link description here

CodePudding user response:

recommendation use better only node.js and express ,axios isn't necesary because express is same

  • Related