Combine Nodejs + React Native + Axios + CORS



我正在尝试使用Axios从前端(反应本)向我的API(node.js)提出请求。但是我对自己的错误感到困惑。这是错误的打印堆栈跟踪:

Network Error
- node_modulesaxioslibcorecreateError.js:16:24 in createError
- node_modulesaxioslibadaptersxhr.js:87:25 in handleError
- node_modulesevent-target-shimlibevent-target.js:172:43 in dispatchEvent
- node_modulesreact-nativeLibrariesNetworkXMLHttpRequest.js:554:29 in setReadyState
- node_modulesreact-nativeLibrariesNetworkXMLHttpRequest.js:387:25 in __didCompleteResponse
- node_modulesreact-nativeLibrariesvendoremitterEventEmitter.js:182:12 in emit
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:302:47 in __callFunction
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:116:26 in <unknown>
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:265:6 in __guard
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:115:17 in callFunctionReturnFlushedQueue

因此,我不确定是否需要使用Axios配置某些内容以允许与后端进行通信,或者我必须配置后端以允许使用前端的请求。这是我对后端服务器的配置。

// 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);
});

其他一切都可以正常工作,我的方法在服务器端得到和帖子起作用。

这是我使用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地址http://192.168.0.123:3001/login的URL。

以下是如何获取PC的IP地址:从Expo App拨打本地托管的服务器

这是一个类似的问题:axios(在反应中)未在local主机中调用服务器

希望将来可以用类似的错误帮助某人。

最新更新