Express doesn't set a cookie

后端 未结 10 1568
花落未央
花落未央 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:14

    One of the main features is to set header correctly.

    For nginx:

    add-header Access-Control-Allow-Origin' 'domain.com';

    add_header 'Access-Control-Allow-Credentials' 'true';

    Add this to your web server.

    Then form cookie like this:

    "cookie": {
            "secure": true, 
            "path": "/", 
            "httpOnly": true, 
            "hostOnly": true, 
            "sameSite": false, 
            "domain" : "domain.com"
        }
    

    The best approach to get cookie from express is to use cookie-parser.

    0 讨论(0)
  • 2020-12-14 02:15

    app.post('/api/user/login',(req,res)=>{
    
        User.findOne({'email':req.body.email},(err,user)=>{
            if(!user) res.json({message: 'Auth failed, user not found'})
            
            user.comparePassword(req.body.password,(err,isMatch)=>{
                if(err) throw err;
                if(!isMatch) return res.status(400).json({
                    message:'Wrong password'
                });
                user.generateToken((err,user)=>{
                    if(err) return res.status(400).send(err);
                    res.cookie('auth',user.token).send('ok')
                })
            }) 
        })
    });

    response

    res.cookie('auth',user.token).send('ok')

    server gives response ok but the cookie is not stored in the browser

    Solution :

    Add Postman Interceptor Extension to chrome which allows postman to store cookie in browser and get back useing requests.

    0 讨论(0)
  • 2020-12-14 02:17

    I had the same issue with cross origin requests, here is how I fixed it. You need to specifically tell browser to allow credentials. With axios, you can specify it to allow credentials on every request like axios.defaults.withCredentials = true however this will be blocked by CORS policy and you need to specify credentials is true on your api like

    const corsOptions = {
        credentials: true,
        ///..other options
      };
    
    app.use(cors(corsOptions));
    

    Update: this only work on localhost For detail answer on issues in production environment, see my answer here

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题