2017-12-24 35 views
2

Axiosを使用してフロントエンド(反応ネイティブ)からAPI(Node.JS)へのリクエストを作成しようとしています。しかし、私が得るエラーについては混乱しています。ここでは、エラーの印刷スタックトレースです:Nodejs + Reactネイティブ+ 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

ANSWER:

さてさて、数時間はそのバグに取り組ん後、私は私の自己で答えを見つけました。私のサーバNode.jsは私のPCで動作しており、携帯電話でExpoで私のアプリをテストしています。私はAxiosとフロントエンドからサーバーを呼び、URLはhttp://localhost:3001/loginでした。私の携帯電話で自分のPCのlocalhostにアクセスできないので、PCのIPアドレスのURLを変更する必要がありました。http://192.168.0.123:3001/loginCalling locally hosted server from Expo App

ここで同様の問題があります:Axios (in React-native) not calling server in localhost

が、それは同様のバグで、将来的に誰かを助けることを願って

はここにあなたのPCのあなたのIPアドレスを取得する方法です。