2016-07-28 50 views
0

给出一些我迄今尝试过的代码。设置请求url的cookie,当起源url和请求url不同时

申请原产地 - “abc.com”,请求的URL - “login.abc.com/login”(Post方法)

function setCookie(req, res) 
{ 
    //Some code goes here. 
    //Code to set cookie 
    res.cookie('test',"some value"); //This should set cookie for login.abc.com, which never happened 
} 

也试过域

设置
function setCookie(req, res) 
{ 
    //Some code goes here. 
    //Code to set cookie 
    res.cookie('test',"some value",{domain:'.abc.com'},{'path' : '/'});//This should set cookie for .abc.com 
} 

下面的代码是按预期工作

申请原产地 - “abc.com”,请求的URL - “abc.com/login”(Post方法)

function setCookie(req, res) 
{ 
    //Some code goes here. 
    //Code to set cookie 
    res.cookie('test',"some value",{domain:'.abc.com'},{'path' : '/'});//This set the cookie for .abc.com successfully 
} 

有人可以帮助我理解为什么它不设置在第一种情况下cookie,但它是在第二种情况下设置cookie?

注意我想在我的本地。

回答

0

因此,最后我得到了解决我的问题,并能够实现我想要的。写下这个答案,以便其他人可以在将来得到好处。

变化的客户端: -

$.ajax({type: "post", 
     data: {}, 
     timeout: 30000, 
     dataType:"json", 
     xhrFields : {withCredentials : true} //Need to add this along with the request. 
    }) 

现在服务器端更改: -

var cors = require('cors'); 

app.post('/testRoute', 
    cors({credentials:true, 
    origin:'http://example.com'}), //Origin should be the url of the page, from where we are sending request. 
    function(req, res){ 

    res.cookie('test',"some value",{'path' : '/'}) 
}) 

参考cors-doc更多地了解如何在服务器端使用cors

注: - 为*如果xhrFields : {withCredentials : true}我们在Ajax请求被指定无法使用Access-Control-Allow-Origin值。