skip to Main Content

I need to add: Access-Control-Allow-Origin: 'http://localhost:8080', because I get an error:

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

But i don’t know how to do it for node js and express js. I tried to add corsOptions to cors, but it doesn’t work:
server.js:

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const app = express();
const config = require('config');
const db = config.get("mongodb.connectionString");
const PORT = config.get("http.port");
const api = require('./routes/api');
const path = require('path')

var corsOptions = {
    origin:  'http://localhost:8080',
    optionsSuccessStatus: 200 // For legacy browser support
}

app.use(cors(corsOptions))
app.use(express.urlencoded({ extended: true }));
app.use(express.json())
app.use('/api', api);
app.use(express.static(path.join(__dirname, 'public')))

mongoose
    .connect(db, {
        useFindAndModify: false,
        useUnifiedTopology: true,
        useNewUrlParser: true,
    })
    .then(() => console.log('Connected to mongodb!'))
    .catch(err => {
        console.log(Error, err.message);
    });

app.listen(PORT, function () {
    console.log('Server running on localhost:' + PORT);
});

How to do it?

Edit:

Response header:

Request URL: https://myServerThatIUse.com/api/get
Referrer Policy: strict-origin-when-cross-origin
Connection: keep-alive
Content-Encoding: gzip
Content-Type: text/html
Date: Mon, 05 Jul 2021 13:19:29 GMT
ETag: W/"60db3d69-70e"
Server: nginx/1.14.2
Transfer-Encoding: chunked
Accept: application/json, text/plain, */ *
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Host: myServerThatIUse.com
Origin: http://localhost:8080
Referer: http://localhost:8080/
sec-ch-ua: " Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"
sec-ch-ua-mobile: ?0
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36

2

Answers


  1. try to add this extension on your chrome

    Login or Signup to reply.
  2. You could do something like this:

    const whitelist = ['http://some-page:3000', 'https://another-page', undefined];
    const dynamicCorsOptions = {
      origin(origin, callback) {
    
        console.log('Origin is: ', origin);
        if (whitelist.indexOf(origin) !== -1) { 
          callback(null, true);
        } else {
          callback(new Error(`${origin} blocked by CORS`));
        }
      },
      methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
      preflightContinue: false,
      optionsSuccessStatus: 204,
      credentials: true,
    };
    

    And then just add this configuration to the route:

    app.use('/api/v1/auth', cors(dynamicCorsOptions), api);
    

    Bear in mind if you are running the API and client on the same machine (locally) the origin will be undefined

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search