You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js后端auth中间件中从请求头Cookie读取JWT令牌

解决方法

首先明确一个核心误区:res.cookie是响应对象的方法,作用是向客户端写入Cookie,而客户端携带的Cookie全部存储在请求对象req中,这是你读取失败的核心原因。

推荐方案:使用cookie-parser中间件(最简便)

这是Express生态下官方推荐的Cookie解析方案,步骤如下:

  1. 安装依赖
npm install cookie-parser
  1. 在Express入口文件(通常是app.js/index.js)中注册中间件,注意要放在路由注册之前:
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();

// 注册Cookie解析中间件
app.use(cookieParser());
// 后续再注册你的路由
// app.use('/', yourRouter)
  1. 注册完成后,你在任意中间件/路由中都可以直接读取解析好的Cookie值,你的auth中间件可以修改为:
const jwt = require('jsonwebtoken');
const User = require('../models/user');

const auth =  async(req, res, next) =>{
    try {
        // 直接读取解析后的token值
        const token = req.cookies.token;
        if(!token) {
            return res.status(401).send('未登录,无权访问');
        }
        // 校验JWT有效性,替换为你自己的JWT签名密钥
        const decoded = jwt.verify(token, '你的JWT_SECRET密钥');
        // 查询对应用户挂载到req对象,后续路由可直接使用
        req.user = await User.findOne({ _id: decoded._id });
        if(!req.user) {
            throw new Error('用户不存在');
        }
        next();
    } catch (error) {
        res.status(401).send('身份认证失败');
    }
}

module.exports = auth;

备选方案:手动解析Cookie字符串

如果你不想引入第三方依赖,可以直接手动解析请求头中的原始Cookie字符串:

const auth =  async(req, res, next) =>{
    // 读取原始Cookie字符串
    const rawCookie = req.headers.cookie;
    let token = null;
    if(rawCookie) {
        // 拆分字符串为键值对
        const cookieMap = rawCookie.split('; ').reduce((result, item) => {
            const [key, value] = item.split('=');
            result[key] = value;
            return result;
        }, {});
        token = cookieMap.token;
    }
    // 后续JWT校验逻辑和上面一致
}

额外说明

你之前读取host字段失败的原因也同理:可以直接通过req.headers.host拿到请求头中的host值,不需要通过其他属性读取。


内容的提问来源于stack exchange,提问作者Alex Antoine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 20:45:00