简体   繁体   中英

Set cors in my express for node.js already but still give the same error about cors

I tried setting cors in my express app already but then it still gives

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.

I am trying to do an ajax request for my login api for experimenting. If input is correct, it will output "Login Success" if not, "Invalid Login ID or Password".
My code

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

This is my ajax request server side code.

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

As for my html code I only

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

This is the response I get when observing the network tab in 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

Did I set something wrongly in cors? I already installed in npm and followed the instructions on the npm cors itself but still give this error saying I dont have cors enabled. Any help is appreciated! Thanks

UPDATE After following Abhyudit Jain solution I don't get that error anymore but what I see is this 此后,控制台无法显示任何错误,控制台仅显示中止并且我的响应被取消

Any idea as to what kind of error is this?

Yes, you did something wrong. You used cors after you used the routes.

If you move app.use(cors()) before app.use('/api', routes) , it will work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM