Issue
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);
});
};
Solution
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);
},
);
Answered By - Elvis Adomnica
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.