Combine Nodejs + React Native + Axios + CORS

2020-04-10 05:42发布

问题:

I am trying to make a request to my API (Node.JS) from the front-end (react-native) using Axios. But I am confused about the error I get. Here's the print stack trace of the error :

Network Error
- node_modules\axios\lib\core\createError.js:16:24 in createError
- node_modules\axios\lib\adapters\xhr.js:87:25 in handleError
- node_modules\event-target-shim\lib\event-target.js:172:43 in dispatchEvent
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:554:29 in setReadyState
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:387:25 in __didCompleteResponse
- node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:182:12 in emit
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:302:47 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:116:26 in <unknown>
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:265:6 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:115:17 in callFunctionReturnFlushedQueue

So I am not sure if I need to configure something with Axios to allow the communication with the back-end or do I have to configure my back-end to allow the requests with the front-end. Here's my configuration of the server of the back-end with CORS :

// server.js
var app = require('./app');

var routes = require('./routes');
var port = process.env.PORT || 3001;
var cors = require('cors');

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

var server = app.listen(port, function(){
    console.log('Express server listening on port ' + port);
});

Everything else works fine, my methods GET and POST works on the server side.

Here's my call with Axios :

import axios from 'axios';

export function loginUser(parameters, onSuccess, onError) {
    axios.post('http://localhost:3001/login', parameters)
    // Succes :
        .then((response) => {
            console.log(response);
        })
        // Echec :
        .catch((error) => {
            console.log(error);
        });
}

回答1:

ANSWER :

Alright, after few hours working on that bug, I found the answer by my self. The thing is that my server Node.js is running on my PC and I am testing my app with Expo on my cellphone. I was calling the server from the front-end with Axios with url http://localhost:3001/login. As I can't reach localhost of my PC with my cellphone, I had to change the url for the IP address of my PC, http://192.168.0.123:3001/login.

Here's how to get your IP address of your PC : Calling locally hosted server from Expo App

Here's a similar problem : Axios (in React-native) not calling server in localhost

Hope it can help someone in the future with a similar bug.