繁体   English   中英

结合Nodejs + React Native + Axios + CORS

[英]Combine Nodejs + React Native + Axios + CORS

我正在尝试使用Axios从前端(本机)向我的API(Node.JS)发出请求。 但是我对我得到的错误感到困惑。 这是错误的打印堆栈跟踪:

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

因此,我不确定是否需要使用Axios配置某些内容以允许与后端通信,还是必须配置后端以允许与前端进行请求。 这是我使用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);
});

其他一切工作正常,我的GET和POST方法在服务器端工作。

这是我给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);
        });
}

回答:

好了,在处理了该错误几个小时之后,我自己找到了答案。 事实是我的服务器Node.js在我的PC上运行,并且我正在手机上通过Expo测试我的应用程序。 我从前端使用Axios通过url http://localhost:3001/login调用服务器。 由于无法用手机访问PC的本地主机,因此必须更改PC IP地址的URL,即http://192.168.0.123:3001/login

这是获取PC IP地址的方法: 从Expo App调用本地托管的服务器

这是一个类似的问题: Axios(在React-native中)不在本地主机中调用服务器

希望它可以在将来解决类似错误的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM