2017-12-24 56 views
2

Axios를 사용하여 프런트 엔드 (반응 네이티브)에서 내 API (Node.JS)에 요청을 보내려고합니다. 그러나 내가 얻는 오류에 대해 혼란 스럽습니다.Nodejs + React Native + Axios + CORS

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); 
     }); 
} 
+1

Axios와 통화하는 방법을 공유 할 수 있습니까? 이 오류는 CORS 오류처럼 보이지 않습니다. – Corey

+1

내가 stackoverflow에 새로운 의견에 코드를 넣어하는 방법을 모르겠지만, 내 게시물을 업데이 트, 미안 해요 – Citrix

답변

1

답변 : 좋아, 그건 버그 작업을 몇 시간 후, 나는 내 자신에 의해 답을 발견

. 문제는 내 서버 Node.js이 내 PC에서 실행 중이고 핸드폰에 Expo으로 내 앱을 테스트하고 있다는 것입니다. 프런트 엔드에서 Axioshttp://localhost:3001/login이라는 URL로 서버를 호출했습니다. 휴대 전화로 내 PC의 localhost에 연결할 수 없기 때문에 내 PC의 IP 주소 인 http://192.168.0.123:3001/login에 대한 URL을 변경해야했습니다. Calling locally hosted server from Expo App

여기에 비슷한 문제가있다 : : Axios (in React-native) not calling server in localhost

이 비슷한 버그와 미래에 다른 사람을 도울 수 있기를 바랍니다

여기 당신의 PC의 IP 주소를 얻는 방법이다.