Ong Kong Tat Ong Kong Tat -3 years ago 102
Node.js Question

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.urlencoded({ extended:true}));

/*'/api', function (req, res) {
var data = req.body;

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

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) {
error: function(response) {

As for my html code I only

<input class="button" type="submit" id="submit" value="Log In"
<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
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

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

After following Abhyudit Jain solution I don't get that error anymore but what I see is this I am not able to identify any error after that with the console only showing abort and my response somehow getting cancelled

Any idea as to what kind of error is this?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download