0

Like to ask a CORS cookie question again, I have spent quite some time on this but cannot resolve it. Here is the situation.

I got a Backend api in nodejs(http://localhost:5000), and a React Frontend app(http://localhost:3000). In Backend side, Cors setting is like this.

private initializeCors(){
    this.app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "http://localhost:3000");
      res.header("Access-Control-Allow-Headers", "Content-Type, Accept");
      res.header("Access-Control-Allow-Credentials", "true");
      next();
    });
  }

I have set { credentials: "include" } in Fetch Api when login with username/password. Set-Cookie has been set in response and I can see it saved in browser. Cookie is with the format "Authorize=TOKEN;HttpOnly;Max-Age=3600;" Cookie in browser

Then when route to another url and it cannot retrieve data from Backend with 401 exception. Here is the code of the sequence call.

const credentialsInclude : "include" | "omit" | "same-origin" | undefined = "include";
function getAllPayments() {
    const requestOptions = {
        method: 'GET',
        credentials: credentialsInclude
    };
    return fetch(apiUrls.GET_ALL_PAYMENTS, requestOptions).then(handleResponse);    
}

I can see the cookie not added into header. No cookie in header

I have followed the best answer of here, but cannot get it work.

Any suggestions? Thanks.

sideshowbarker
  • 62,215
  • 21
  • 143
  • 153
Andrew
  • 9
  • 3

1 Answers1

0

I have just figured out. The issue was not caused by the CORS settings. It caused by the Cookie itself. For my case, I need to add Path=/; into Set-Cookie in response headers. So that the cookie from response could be added to sequenced requests after successful login.

Andrew
  • 9
  • 3