Shrabanee Shrabanee - 4 months ago 14
HTTP Question

Setting cookie for request-url, when origin url and request url are different

Giving some code that I have tried so far.


Request-origin - "abc.com", Request-url - "login.abc.com/login" (Post method)


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
}


Also tried to set for domain

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
}


Following code is working as expected


Request-origin - "abc.com", Request-url - "abc.com/login" (Post method)


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
}


Can someone help me to understand why it is not setting cookie in the first case but it is setting cookie in the second case?

NOTE I am trying this in my local.

Answer

So finally I got the solution to my issue and able to achieve what I want. Writing this answer, so that some one else can get benifit in the future.

Changes in client side:-

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

Now server side changes:-

 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' : '/'})
 })

Refer cors-doc to know more about how to use cors in server side.

NOTE:- Can not use Access-Control-Allow-Origin value as * if xhrFields : {withCredentials : true} we are specifying in the ajax request.