在我的express中为node.js设置了cors,但仍然给出了关于cors的相同错误

时间:2017-06-14 04:03:24

标签: node.js ajax express 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请求服务器端代码。

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

至于我的HTML代码我只

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

这是我在chrome 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

我在cors中错误地设置了什么吗?我已经安装在npm并按照npm cors本身的说明进行操作,但仍然提出此错误,说我没有启用cors。任何帮助表示赞赏!感谢

更新 在遵循Abhyudit Jain解决方案后,我不会再出现该错误,但我看到的是I am not able to identify any error after that with the console only showing abort and my response somehow getting cancelled

知道这是什么类型的错误吗?

1 个答案:

答案 0 :(得分:2)

是的,你做错了什么。你使用这些路线之后就用了火箭。

如果您在app.use(cors())之前移动app.use('/api', routes),它将正常工作。