在我的应用程序中,我需要使用快捷框架设置一个cookie。我已经尝试了下面的代码,但它没有设置cookie。

var express = require('express'), http = require('http');
var app = express();
app.configure(function(){
      app.use(express.cookieParser());
      app.use(express.static(__dirname + '/public'));

      app.use(function (req, res) {
           var randomNumber=Math.random().toString();
           randomNumber=randomNumber.substring(2,randomNumber.length);
           res.cookie('cokkieName',randomNumber, { maxAge: 900000, httpOnly: true })

           console.log('cookie have created successfully');
      });

});

var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(5555);

当前回答

饼干?

res.cookie('cookieName', 'cookieValue')

读过饼干吗?

req.cookies

Demo

const express('express')
    , cookieParser = require('cookie-parser'); // in order to read cookie sent from client

app.get('/', (req,res)=>{

    // read cookies
    console.log(req.cookies) 

    let options = {
        maxAge: 1000 * 60 * 15, // would expire after 15 minutes
        httpOnly: true, // The cookie only accessible by the web server
        signed: true // Indicates if the cookie should be signed
    }

    // Set cookie
    res.cookie('cookieName', 'cookieValue', options) // options is optional
    res.send('')

})

其他回答

同构读cookie助手:

function getCookieValue(cookieName = '', cookie = '') {
  const matches = cookie.match(`(^|[^;]+)\\s*${cookieName}\\s*=\\s*([^;]+)`)
  return matches ? matches.pop() : ''
}

// Node with express:
getCookieValue('cookieName', req.headers.cookie)

// Browser:
getCookieValue('cookieName', document.cookie)

用express写入节点:

res.cookie('cookieName', 'cookieValue')

在浏览器中编写:

function setCookie(
  cname,
  cvalue,
  exdays = 100 * 365 /* 100 days */
) {
  const now = new Date()
  const expireMs = exdays * 24 * 60 * 60 * 1000
  now.setTime(now.getTime() + expireMs)

  document.cookie = `${cname}=${cvalue};expires=${now.toUTCString()};path=/`
}

// Example of usage
setCookie('cookieName', 'cookieValue')

在express中设置cookie非常简单

首先安装cookie-parser

npm install cookie-parser

使用中间件

const cookieParser = require('cookie-parser');
app.use(cookieParser());

设置cookie了解更多

res.cookie('cookieName', '1', { expires: new Date(Date.now() + 900000), httpOnly: true })

访问cookie可以了解更多信息

console.dir(req.cookies.cookieName)

完成了!

设置cookie:

res.cookie('cookie', 'monster')

https://expressjs.com/en/4x/api.html#res.cookie

读饼干: (使用cookie-解析器中间件)

req.cookies['cookie']

https://expressjs.com/en/4x/api.html#req.cookies

我不是在回答你的问题,但我在寻找一个问题的答案时,遇到了你的问题。也许它会帮助其他人。

我的问题是在服务器响应中设置了cookie,但浏览器没有保存。

服务器返回设置了cookie的响应:

Set-Cookie:my_cookie=HelloWorld; Path=/; Expires=Wed, 15 Mar 2017 15:59:59 GMT 

我就是这样解出来的。

我在客户端代码中使用了fetch。如果您没有在获取选项中指定凭据:'include', cookie既不会发送到服务器也不会被浏览器保存,即使服务器响应设置了cookie。

例子:

var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');

return fetch('/your/server_endpoint', {
    method: 'POST',
    mode: 'same-origin',
    redirect: 'follow',
    credentials: 'include', // Don't forget to specify this if you need cookies
    headers: headers,
    body: JSON.stringify({
        first_name: 'John',
        last_name: 'Doe'
    })
})

如果您在为一个请求设置多个cookie时有问题

试试这个方法:

res.setHeader('Set-Cookie', [
    `accessToken=${accessToken}; HttpOnly; Path=/; Max-Age=${60 * 60}; Secure=True;`,
    `refreshToken=${refreshToken}; HttpOnly; Path=/; Max-Age=${60 * 60 * 24 * 7 * 2}; Secure=True;`
]);