Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 810
strangeQuirks Avatar asked Oct 23 '25 09:10

strangeQuirks


1 Answers

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;
like image 137
Roger Jacob Avatar answered Oct 25 '25 23:10

Roger Jacob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!