NodeJs no 'Access-Control-Allow-Origin' header is present on the requested resource

Dung Do Tien Jan 28 2022 66

Hello Guys, I am a newbie with Node.js and Express.js and I tried to create a very basic server and return a list students as below:

// Create node server with express   
var express = require('express');
var app = express();
var students = [
    {   
     "id": "1", 
     "name": "Duc",
     "class": "12B2"
    },
    {   
     "id": "2", 
     "name": "Nam",
     "class": "11C1"
    },
    {   
     "id": "3", 
     "name": "Trung",
     "class": "10A1"
    }
];

app.use(express.bodyParser());

app.get('/', function(req, res) {
  res.json(students);
});
app.listen(process.env.PORT || 3000);
console.log('Server is running on Port 3000')

It's run very well for me, but when I use Ajax to call this link(localhost:3000) to get list student data as below:

$.get("http://localhost:3000", function(data, status){
    alert("Data: " + data + "\nStatus: " + status);
});

I got an exception throw XMLHttpRequest cannot load localhost:3000. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:4000' is therefore not allowed access.

XMLHttpRequest cannot load localhost:3000. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:8888' is therefore not allowed access."

localhost:4000 is my client app, call localhost:3000 to get data.

I create the project in the Nodejs version v12.18.3 and Window 10.

How can I resolve it?

Have 3 answer(s) found.
  • T

    Trump McDonald Jan 28 2022

    You need to add CORS to allow another site can access to your server to get data.

    To allow this, you need to turn CORS on when you instantiate your Express server as below(before you write app.get("/")):

    app.use(function (req, res, next) {
    
        res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4000');
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
        res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
        res.setHeader('Access-Control-Allow-Credentials', true);
    
        next();
    });

    This is a middleware to help allow http://localhost:4000 can access to http://localhost:3000.

  • A

    Amina Khaled Jan 28 2022

    You can change:

    app.get('/', function(req, res) {
      res.json(students);
    });

    To

    app.get('/', function (req, res) {
        res.header("Access-Control-Allow-Origin", "*");
        res.json(students);
    })

    It's really worked for me.

  • N

    Nguyen Truong Giang Jan 28 2022

    You can use cors package to help resolve your problem. You can add more core below inside your Node server:

    const cors = require('cors');
    const corsOptions ={
        origin:'http://localhost:4000', 
        credentials:true,
        optionSuccessStatus:200
    }
    app.use(cors(corsOptions));

    It worked for me!

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close