Express doesn't set a cookie

后端 未结 10 1600
花落未央
花落未央 2020-12-14 01:45

I have problem with setting a cookies via express. I\'m using Este.js dev stack and I try to set a cookie in API auth /login route. Here is the cod

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 02:24

    i work with express 4 and node 7.4 and angular,I had the same problem me help this:
    a) server side: in file app.js i give headers to all response like:

     app.use(function(req, res, next) {  
          res.header('Access-Control-Allow-Origin', req.headers.origin);
          res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
          next();
     });  
    

    this must have before all router.
    I saw a lot of added this headers:

    res.header("Access-Control-Allow-Headers","*");
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    

    but i dont need that,

    b) when you definer cookie you nee add httpOnly: false, like:

     res.cookie( key, value,{ maxAge: 1000 * 60 * 10, httpOnly: false });
    

    c) client side: in send ajax you need add: "withCredentials: true," like:

    $http({
         method: 'POST',
         url: 'url, 
         withCredentials: true,
         data : {}
       }).then(function(response){
            // code  
       }, function (response) {
             // code 
       });
    

    good luck.

提交回复
热议问题