Set Client-Side Accessible Cookie In Express

后端 未结 3 1370
借酒劲吻你
借酒劲吻你 2021-01-30 21:56

I\'m working on a Node app that uses Express and SocketIO. I want to set a cookie in my Express controller which is then accessible from my client-side Javascript code. Everythi

3条回答
  •  不思量自难忘°
    2021-01-30 22:24

    Figured it out! By default Express sets the option httpOnly to true. This means that your cookies cannot be accessed by the client-side Javascript. In order to correctly set cookies accessible on the client just use a snippet like the following:

    res.cookie('rememberme', 'yes', { maxAge: 900000, httpOnly: false});
    

    I've also noticed that if you call this command and then call res.redirect, the cookie won't get set. This command needs to be followed by res.render at some point in order for it to work. Not sure why this is.

提交回复
热议问题