Cit*_*rix 3 node.js cors react-native axios
我正在尝试使用Axios从前端(react-native)向我的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
Run Code Online (Sandbox Code Playgroud)
因此,我不确定是否需要使用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);
});
Run Code Online (Sandbox Code Playgroud)
其他一切正常,我的方法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);
});
}
Run Code Online (Sandbox Code Playgroud)
Cit*_*rix 10
答案:
好吧,经过几个小时的工作,我找到了自己的答案.问题是我的服务器Node.js在我的电脑上运行,而我正在用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中)不在localhost中调用服务器
希望它可以帮助将来有类似的bug.
| 归档时间: |
|
| 查看次数: |
2849 次 |
| 最近记录: |