简体   繁体   中英

Issue getting CORS to work with JQuery client, Node / Express server

I am having an issue getting cross origin resource sharing working with cookies. Here is my setup:

Client:

    $.ajax({
        type: 'POST',
        url: '/processReq',
        data: params,
        xhrFields: {withCredentials:true},
        crossDomain: true,
        success: ...
    });

I have debugged the client in the browser, and have verified that XMLHttpRequest.withCredentials is in fact true.

Server:

I am setting the following headers:

res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', '*');

My issue is that I cannot get the session cookie to be stored by the browser, and sent on a subsequent request to the server.

Here are the response headers in the browser:

{
    "server": "nginx/1.2.6",
    "date": "Fri, 01 Feb 2013 23:46:07 GMT",
    "content-type": "application/json; charset=utf-8",
    "content-length": "306",
    "connection": "keep-alive",
    "x-powered-by": "Express",
    "access-control-allow-credentials": "true",
    "access-control-allow-origin": "*",
    "set-cookie": [
        "id=s%3Azm1m...NXe4Lkr9rLw; Domain=api.mydomain.io; Path=/; Expires=Sat, 01 Feb 2014 23:46:07 GMT; HttpOnly"
    ]
}

Every time I test, I do not get a cookie sent to the server. Am I missing something? Any help is much appreciated.

You cannot use ('Access-Control-Allow-Origin', '*') with ('Access-Control-Allow-Credentials', true) . You need to explicitly set the Access-Control-Allow-Origin to one value. If you still want the '*' behavior, set the value to the requests origin header programatically.

From https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS?redirectlocale=en-US&redirectslug=HTTP_access_control :

Important note: when responding to a credentialed request, server must specify a domain, and cannot use wild carding.

Another elegant option that side-steps CORS altogether is using a hidden iframe and window.postMessage .

The postMessage API let's two browser frames communicate cross-domain. The basic design is as follows:

  1. load main page on domain-1.com
  2. main page loads hidden iframe from domain-2.com
  3. hidden iframe loads javascript to interface with domain-2.com APIs

Any time the main page wishes to talk cross-domain, it proxies the request through the hidden iframe. There is no CORS to deal with — none!

A Few Tutorials:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM