Skip to content Skip to sidebar Skip to footer

Can't Allow Cross-Origin Request In Local Nodejs Server

I've created a local REST API server in nodejs, which is fetching data from local Mongodb database. I've also created a basic web page, which request this data from the server loca

Solution 1:

Does your request require a pre-flight response? If it does, it will be trying to hit your endpoint with method 'OPTIONS' and unless you have set one up, you will see the cors issue.

So if you find that the preflight response is failing, you can either add a custom options route, or potential use the npm cors package - https://www.npmjs.com/package/cors

npm install cors --save

In your app.js

var cors = require('cors')


app.options('*', cors()) // include before other routes 
app.use(cors())

Solution 2:

I finally figured out the solution by adding those headers in my routes as following:

routes/todos.js

...
...
router.get('/', function(req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // If needed
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,contenttype'); // If needed
res.setHeader('Access-Control-Allow-Credentials', true); // If needed

res.send('cors problem fixed:)');
});

Solution 3:

Please move the header code after var app = express(); That mean you must place them before define router.

var app = express();
app.use(function (req, res, next) {
    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT,    PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

// Router

Solution 4:

You might have to add:

 res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

Why? Well I think I had the same problem and this solved it for me.


Post a Comment for "Can't Allow Cross-Origin Request In Local Nodejs Server"