-1

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
Weronika
  • 368
  • 3
  • 24
  • 2
    Who is in control of `example.com` here in this scenario? (You are aware that _this_ is the party here that must allow this, yes?) – CBroe Jul 05 '21 at 11:50
  • Maybe I wrote it wrong, it's my server `http://localhost:3000`, I'm just connecting it to the domain and I get this error that's why i gave this url – Weronika Jul 05 '21 at 11:54
  • Because first it was saying `example.com` cannot be accessed from `localhost:8080` or something. After edit it makes sense now. – Aritra Chakraborty Jul 05 '21 at 12:03
  • Honestly, your config should work. Can you check in your browser console what Response header are u getting? Specifically if it has `Access-Control-Allow-Origin: http://localhost:8080` – Aritra Chakraborty Jul 05 '21 at 12:05
  • It's `Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://localhost:8080` so it should work but I still get an error: `'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.` – Weronika Jul 05 '21 at 12:17
  • If you use chrome or chrome-based browser, please check this: https://stackoverflow.com/questions/10883211/why-does-my-http-localhost-cors-origin-not-work. Probably, changing hostname from `localhost` to smth like `localhost.localdomain` or just 'lvh.me' will help. – Igor Goyda Jul 05 '21 at 12:23
  • @IgorGoyda I tried on firefox browser and I still get this error – Weronika Jul 05 '21 at 13:00
  • 1
    You probably want to consider going in to the Network pane in browser devtool and capturing the actually response headers shown there, and then editing/updating the question to paste in the exactly response headers shown there. – sideshowbarker Jul 05 '21 at 13:17
  • @sideshowbarker I edited my question, `myServerThatIUse.com` is my backend that I use and work on it – Weronika Jul 05 '21 at 13:28
  • The headers shown in the question now appear to be the request headers, not the response headers… – sideshowbarker Jul 05 '21 at 15:02

2 Answers2

1

try to add this extension on your chrome

Jay gajjar
  • 150
  • 8
1

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

Patrik Bego
  • 4,009
  • 1
  • 26
  • 24
  • What is authRouter? I get an error `ReferenceError: authRouter is not defined` – Weronika Jul 05 '21 at 12:11
  • In you case it is `api` – Patrik Bego Jul 05 '21 at 12:13
  • Did you remove `pp.use(cors(corsOptions))` – Patrik Bego Jul 05 '21 at 12:17
  • Yes, but on my browser console Response header there is `Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://localhost:8080` so looks like it's working but I still get his error about `No 'Access-Control-Allow-Origin' header` – Weronika Jul 05 '21 at 12:20
  • In that case i would try to debug it and see If it hits the cors filter. Or put there console.log('origin: ', origin) and check the value. If it is not there, is most likely some other misconfiguration, else try to add HTTP://localhost:8080 to the list ... otherwise out of ideas :P – Patrik Bego Jul 05 '21 at 12:26
  • After use `console.log('origin: ', origin) ` before `callback` in `dynamicCorsOptions` I get nothing. What could be wrong? – Weronika Jul 05 '21 at 12:32
  • Try it again, i updated the code (put the log statement inside of origin method) – Patrik Bego Jul 05 '21 at 12:36
  • After update I still doesn't see any `console.log `. I add it here: `if (whitelist.indexOf(origin) !== -1) { console.log('origin: ', origin) callback(null, true);}` – Weronika Jul 05 '21 at 12:40