strangeQuirks
strangeQuirks

Reputation: 5920

ExpressJS: Request has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

In my browser developer toolbar I get the following error message for a POST request:

Access to XMLHttpRequest at 'http://localhost:8000/api/tags/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

However when I look into my server.js I do allow access:

app.prepare().then(() => {
    const server = express();

    server.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next();
    });

Does anyone know why this is blocked now

Upvotes: 4

Views: 28180

Answers (2)

Burak Dalkıran
Burak Dalkıran

Reputation: 1

These were working before. I noticed that it is not working now, I have no idea why there is such a change. I'm sure there is a solution without using packages like in @roger-jacob's answer. Adding a package to the project makes us go through a bureaucratic process.

res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Con`enter code here`trol-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, 
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

Upvotes: 0

Roger Jacob
Roger Jacob

Reputation: 360

Better to use the "cors" package as follows.

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
app.use(cors());

// some route controllers
const customRoute = require('./customRoute.controller');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


// Custom routes
app.use('/api/tags', customRoute);

app.use(express.static(path.join(__dirname, 'dist')));


// Catch all other routes & return index file
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

module.exports = app;

Upvotes: 7

Related Questions