Unable to set cookie in browser using request and express modules in NodeJS

后端 未结 2 878

I am having a client and a server node written in express. The client communicates with server using request module, the server will send response back to the client. Here i

2条回答
  •  孤城傲影
    2021-01-20 21:19

    Client browser for first hit to 7000 api will not contain any cookie, thus req.cookies will log {}, thus we have to set cookie in the res for the client browser to send the cookie for the rest requests.

    Solution (Client Code):

    if (200 == response.statusCode) {
    
        // For first request it will be empty {}
        console.log(req.cookies);
    
        /* fetching the cookie from the response header
         * and setting in res to be set in the browser
         */
        var c = response.headers['set-cookie'];
        res.set('set-cookie',c[0]);
    
        res.send('Done');
    
    }
    

    Explanation: What you are doing is trying to fetch cookies from req which does not contain any cookie. The response object you are getting from hitting the 9000 api will contain the cookie. Thus, you have to set the cookie from response to the res for client browser.

提交回复
热议问题