skip to Main Content

I am trying to connect my react native app with my node js app in the Windows system. Via Postman I am able to get response from node API, but getting undefined as response from react native app.

IPv4 Address :- 192.168.1.5

Node js / index.js file

require('./config/mongoose')
require('dotenv').config()

const app = require('./app')
const port = process.env.PORT

app.listen(8000, '192.168.1.5')

React native files

axios.js

import axios from 'axios';
import EncryptedStorage from 'react-native-encrypted-storage';

const axiosInstance = axios.create({
  baseURL: 'http://192.168.1.5:8000/api/',
  timeout: 10000,
  // headers: headers
});

axiosInstance.interceptors.response.use(
  function (response) {
    // nothing to do
  },
  function (error) {
    EncryptedStorage.removeItem('accessToken');
    EncryptedStorage.removeItem('user');
    axiosInstance.defaults.headers.common['Authorization'] = '';
    return Promise.reject(error);
  },
);

axiosInstance.defaults.headers.common['Content-Type'] = 'application/json';
axiosInstance.defaults.headers.common['Accept'] = 'application/json';

export default axiosInstance;

function that calls the api

const signIn = async (username: string, password: string) => {
    let token = null;
    let user = {};

    console.log(username +'--'+ password);   // data prints correctly

    await axiosInstance
        .post('login', {username, password})
        .then(response => {
            console.log(response);   // undefined
            let res = response.data;

            helpers.showToast(res.message);

            if (res.status) {
                // some other staff
            }
        })
        .catch(e => {
            helpers.showToast(e.message);
            console.log('Error Signin: ', e.message);
        });
};

2

Answers


  1. Have you tried using ngrok?

    npm i ngrok -g 
    

    Then open another terminal. And run :

    ngrok http 8000 // the port you're using on node
    

    It will then display an alternative link that you can use to test with your Node.

    Then copy the generated link, e.g. http://8084-167-913-145-700.eu.ngrok.io, and test to see if it solves your problem

    Login or Signup to reply.
  2. This is not a networking issue but an axios interceptors one. With postman there is no axios and no interceptors, however, your react native code has one and you forgot to return the response in the interceptor:

    axiosInstance.interceptors.response.use(
      function (response) {
        // nothing to do but still return response
        return response;
    
      },
      function (error) {
        EncryptedStorage.removeItem('accessToken');
        EncryptedStorage.removeItem('user');
        axiosInstance.defaults.headers.common['Authorization'] = '';
        return Promise.reject(error);
      },
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search