Nodejs connect.utils.parseSignedCookie不能用,那用什么代替呢?

Nodejs connect.utils.parseSignedCookie不能用,那用什么代替呢?

最近在做socket.io相关的操作,需要用到connect.utils.parseSignedCookie。 得知 utils 属于私用方法,现在的版本已经删除了。

那用什么可以代替 connect.utils.parseSignedCookie 的功能呢?

4 回复

当您发现 connect.utils.parseSignedCookie 已经被移除时,您可以使用 cookie-parser 中的 signedCookie 方法来替代它。cookie-parser 是一个常用的中间件,用于解析和验证签名的 cookie。

示例代码

首先,确保你已经安装了 cookie-parser

npm install cookie-parser

然后,在您的应用中引入并使用 cookie-parser

const express = require('express');
const cookieParser = require('cookie-parser');

const app = express();

// 使用 cookie-parser 中间件,并提供一个密钥用于签名 cookie
app.use(cookieParser('your_secret_key'));

app.get('/', (req, res) => {
    // 获取签名的 cookie 值
    const signedCookieValue = req.signedCookies['your_cookie_name'];
    
    if (signedCookieValue) {
        res.send(`Parsed signed cookie: ${signedCookieValue}`);
    } else {
        res.send('No signed cookie found.');
    }
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

解释

  1. 引入模块:我们首先引入 cookie-parser 模块。
  2. 使用中间件:通过调用 app.use(cookieParser('your_secret_key')) 来初始化 cookie-parser,其中 'your_secret_key' 是用于签名 cookie 的密钥。
  3. 获取签名的 cookie:在路由处理函数中,通过 req.signedCookies['your_cookie_name'] 获取签名的 cookie 值。req.signedCookies 是一个对象,包含了所有已解析的签名 cookie。

这种方法不仅解决了 connect.utils.parseSignedCookie 不可用的问题,还提供了一种更现代且维护性更好的方式来处理签名 cookie。


没有人知道吗? 那只能从旧版本去获取utils了。

/**
 * Parse a signed cookie string, return the decoded value
 *
 * [@param](/user/param) {String} str signed cookie string
 * [@param](/user/param) {String} secret
 * [@return](/user/return) {String} decoded value
 * [@api](/user/api) private
 */

exports.parseSignedCookie = function(str, secret){
  return 0 == str.indexOf('s:')
    ? signature.unsign(str.slice(2), secret)
    : str;
};

通过翻看之前的源代码发现

这里面引入了 cookie-signature 这个包,接着做了以上的处理,接下来知道怎么办了。

在较新版本的 express 中,connect.utils.parseSignedCookie 已经被移除。你可以使用 cookie-parser 中的 signedCookie 方法来替代它。

示例代码

  1. 首先,你需要安装 cookie-parser

    npm install cookie-parser
    
  2. 然后在你的 Node.js 应用中引入并配置 cookie-parser

    const express = require('express');
    const cookieParser = require('cookie-parser');
    
    const app = express();
    
    // 使用 cookie-parser 中间件,并提供一个密钥用于签名
    app.use(cookieParser('your-secret-key'));
    
  3. 使用 req.signedCookies 来访问已签名的 cookie:

    app.get('/', (req, res) => {
      // 访问名为 'example' 的已签名 cookie
      const signedCookieValue = req.signedCookies['example'];
      
      if (signedCookieValue) {
        res.send(`已签名的 cookie 值为: ${signedCookieValue}`);
      } else {
        res.send('未找到已签名的 cookie');
      }
    });
    

解释

  • cookie-parser 是一个中间件,它解析客户端发送过来的 Cookie 字符串,并将它们作为对象添加到请求对象 req.cookies 上。
  • 如果你在使用 cookie-parser 时提供了密钥(例如 'your-secret-key'),那么它还会自动处理已签名的 Cookie,并将它们存储在 req.signedCookies 对象上。
  • req.signedCookies 是一个包含所有已签名 Cookie 的对象,其键是 Cookie 的名称,值是解码后的 Cookie 值。
  • 这样你就可以像以前使用 connect.utils.parseSignedCookie 一样,轻松地访问和验证已签名的 Cookie 了。
回到顶部