cli-api-mocker icon indicating copy to clipboard operation
cli-api-mocker copied to clipboard

cors issue when request was made with credentials

Open joes-code opened this issue 5 years ago • 4 comments

Chrome will block the request with credentials enabled (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials) to mock server because the server returns " Access-Control-Allow-Origin: * "

It's an easy fix - we just need to pass custom cors options to express. I was gonna submit PR but can't seem to push the branch - getting 403.

joes-code avatar Sep 30 '19 11:09 joes-code

We are already using CORS headers. It should work already. You can see how we enable CORS headers here: https://github.com/muratcorlu/cli-api-mocker/blob/master/src/index.js#L73

muratcorlu avatar Sep 30 '19 11:09 muratcorlu

Yep, by default "cors()" set the Access-Control-Allow-Origin to "*" which Chrome will reject when the request was made with "credentials" flag enabled. It throws error something like: A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true All you need to do it update that line #73 to something like this:

var corsOptionsDelegate = function (req, callback) {
  var corsOptions = { 
    origin: true, 
    credentials: true,
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    preflightContinue: false,
    optionsSuccessStatus: 204
  };
  callback(null, corsOptions);
};
app.use(cors(corsOptionsDelegate));

joes-code avatar Sep 30 '19 12:09 joes-code

I'll try to reproduce problem with an example and understand what is exactly needed for fixing it.

muratcorlu avatar Oct 01 '19 18:10 muratcorlu

Hi muratcorlu,

I this issue solved. I am also getting the same issue Access-Control-Allow-Origin to "*"

Yep, by default "cors()" set the Access-Control-Allow-Origin to "*" which Chrome will reject when the request was made with "credentials" flag enabled. It throws error something like: A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true All you need to do it update that line #73 to something like this:

var corsOptionsDelegate = function (req, callback) {
  var corsOptions = { 
    origin: true, 
    credentials: true,
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    preflightContinue: false,
    optionsSuccessStatus: 204
  };
  callback(null, corsOptions);
};
app.use(cors(corsOptionsDelegate));

viv3kk avatar Apr 21 '20 11:04 viv3kk