2017-06-14 1 views
0

について同じエラーを与えるが、それはまだ私がやろうとしています設定CORSすでにそれでも、私はすでに私の急行アプリでCORSを設定しようとしたCORS

XMLHttpRequest cannot load http://localhost:3000/api/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

います私のログインapiのためにajaxリクエストを試してみてください。入力が正しい場合は、「ログイン成功」を出力します。「ログインIDまたはパスワードが無効です」と表示されます。
私のコード

var express = require('express'); 
var bodyParser = require('body-parser'); 
var app = express(); 
var routes = require('./routes'); 
var cors = require('cors'); 

app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended:true})); 
app.use('/api',routes); 
app.use(cors()); 

/*app.post('/api', function (req, res) { 
var data = req.body; 
console.log(data); 
res.sendStatus(200); 
});*/ 

app.listen(3000, function() { 
console.log('Example app listening on port 3000!') 
}); 

これは私のAJAXリクエストサーバ側のコードです。私のhtmlコードについては

function login(){ 

var username = $('#userID').val(); 
var password = $('#Password').val(); 
var postData = { "userID": username, "Password": password }; 
var postJSON = JSON.stringify(postData); 

$.ajax({ 
    url: "http://localhost:3000/api/login", // server url 
    type: "POST", //POST or GET 
    contentType: "application/json", 
    data: postJSON, // data to send in ajax format or querystring format 
    dataType : "json", 
    success: function(response) { 
     alert('success'); 
     console.log(response); 
     $("#result").val(response); 
     window.location.replace("http://localhost/index.html"); 
    }, 
    error: function(response) { 
     alert('error'); 
    } 
    }); 
    } 

私だけ

<input class="button" type="submit" id="submit" value="Log In" 
onclick="login()"/> 
     <div id="result"></div> 

これはクロムF12でネットワークタブを観察したときに私が得る応答です。

Request URL:http://localhost/ 
Referrer Policy:no-referrer-when-downgrade 
Request Headers 
Provisional headers are shown 
Content-Type:application/x-www-form-urlencoded 
Origin:http://localhost 
Referer:http://localhost/ 
Upgrade-Insecure-Requests:1 
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 
(KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 
Form Data 
view source 
view URL encoded 
userID:SDD 
Password:KKK 

私は何かを間違って設定しましたか?私はすでにnpmにインストールし、npm cors自体の指示に従っていましたが、まだこのエラーは、私はcorsを有効にしていないと言っています。どんな助けもありがとう! Abhyuditジャイナ教のソリューションを以下の後、私はもうそのエラーを取得しますが、私が見てもエラーの種類に、このI am not able to identify any error after that with the console only showing abort and my response somehow getting cancelled

任意のアイデアではありませんおかげ

UPDATE はこれですか?

答えて

2

はい、間違ったことをしました。ルートを使用した後でcorsを使用しました。

app.use('/api', routes)の前にapp.use(cors())を移動すると正常に動作します。

+0

私はあなたの解決策に応じて更新しましたが、それは機能しましたが、今は別のエラーに遭遇します。 –

+0

エラーを説明していない限り、どうすればよいですか?ちなみに、あなたの質問に答えられたら、これを正しい答えとして受け入れてください。 –

+0

私はすでに質問に入れています –

関連する問題