3

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

strangeQuirks
  • 4,761
  • 9
  • 40
  • 67
  • Just to make sure, in which port are using that middleware code? also make sure that you are putting it before the routes – evgeni fotia Mar 14 '19 at 19:16
  • where to I see that? – strangeQuirks Mar 14 '19 at 19:21
  • you have a server listening to `http://localhost:8000` and another one listening to `http://localhost:3000` I just want to make sure that the middleware is in the one listening to `http://localhost:8000`. Also make sure that the middleware is defined before the routes – evgeni fotia Mar 14 '19 at 19:27
  • Possible duplicate of [No 'Access-Control-Allow-Origin' - Node / Apache Port Issue](https://stackoverflow.com/questions/18310394/no-access-control-allow-origin-node-apache-port-issue) – Akshay Gulhane Mar 15 '19 at 05:04

1 Answers1

7

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;
Roger Jacob
  • 350
  • 2
  • 11