Nodejs cannot set cookie across domains (across port numbers)?

  node.js, question

Scenario recurrence:

Two services were started on one computer, one using gulp’s pure front-end service (address:http://a.site.com:8080/), one is nodejs service (address:http://a.site.com:8888/), open in the browserhttp://a.site.com:8080/dist/# …, use get requesthttp://a.site.com:8888/wx-edu …A cookie is set in nodejs, and can be seen in the response header of get request, as shown in the figure:

clipboard.png

clipboard.png

However, it is not displayed in chrome’s console in the browser, as shown in the figure:

clipboard.png

Why is this so? Is it because of cross-domain? Please ask your colleagues to help you use java. In case of cross-domain, it can be displayed on chrome console, but when using ajax again, cookie is not added to the request header and returned to the back end.


code area

js:

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7加, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    
    }
  }
xmlhttp.open("GET","http://a.site.com:8888/wx-education/test/test.htm",true);
xmlhttp.send();

Nodejs code:

Method 1:

app.use( session({resave:true,saveUninitialized:
true,key:’ccc’,secret: ‘12345’, cookie: { domain:’.site.com’,
httpOnly:false, maxAge: 600000 } }) );

Method 2:

res.cookie(“ccc”, “123456”, {domain: ‘.site.com’, path: ‘/’, expires:
New Date(Date.now () plus 900000), httpOnly:false};

Method 3:

res.writeHead(200, {
 'Access-Control-Allow-Origin': '*',
 'Set-Cookie': 'myCookie=test;     Domain=site.com;     Path=/;'  ,
 'Content-Type': 'text/plain'
 });

All three nodejs cookie setting methods have been tried, and the results are consistent. They are only displayed in the response header and not in chrome’s Application

Another strange thing is that jquery is used in js to initiate ajax requests. The request is successful, the data is returned normally, and the response result is consistent with the original (i.e. only cookie is displayed in the response header, not in the Application). However, ajax in jquery has entered the failure module.

$.ajax({
 url:  'http://a.site.com:8888/wx-education/test/test.htm' ,
 type: 'get',
 dataType: 'json',
 success:function(data){
 console.log("success");  //Do not execute
 },
 error:function(data){
 console.log("error");  //Execute
 bracket
 });

Please help the great gods to dispel doubts, thank you very much.

If you need to go across domainsAJAXSendcookie, which needs to be openedwithCredentials

xmlhttp.withCrendentials = true;

For this attribute to take effect, the server must explicitly returnAccess-Control-Allow-CredentialsThis header information.

Access-Control-Allow-Credentials: true