如何通过nodejs上的header将jwt token发送到前端?

问题描述 投票:0回答:1

好的,我有一个简单的应用程序。当用户登录时,我使用 jwt 创建一个令牌。我一直在使用 res.cookie() 将令牌发送到前端,但由于原因,我无法再使用 cookie,我如何使用 headers 来实现相同的目标?

基本上,这就是我想要实现的目标:

//登录功能

const login = async (req, res) => {
    const {email, password} = req.body
    
    const user = await User.findOne({email})
    if(!user){
        throw new UnauthenticatedError('Invalid credentials')
    }

    const isPasswordCorrect = await user.comparePassword(password)
    if(!isPasswordCorrect){
        throw new UnauthenticatedError('Invalid credentials')
    }

    const token = user.createJWT()
    res.cookie("token", token).json(user)     //send token here to the frontend through headers instead of cookies
}

//Auth中间件验证token:

const authMiddleware = async (req, res, next) => {
    const {token} = req.cookies    //get the token here from the headers instead of cookies

    if(token){
        try{

            const {userId, name} = jwt.verify(token, process.env.JWT_SECRET)
            req.user = {userId, name}  
            next()
        }
        catch(error){
            throw new UnauthenticatedError('Authentication invalid')
        }
    }else{
        throw new UnauthenticatedError('no token')
    }
}

//前端登录组件

const handleLogin = async (e) => {
        e.preventDefault()
        try {
            const {data} = await axios.post('/auth/login', {email,password})
            successfulNotification('login successful')
            setUser(data)
            setRedirect(true)
        } catch (error) {
            errorNotification('login unsuccessful, please try again later')
            return error
        }        
    }
javascript node.js authentication cookies jwt
1个回答
0
投票

NodeJS HTTP 文档,您可以使用它来设置标头:

res.setHeader("name", "value");

来自 Express 文档

res.set("name", "value");

您还可以一次为多个标头传递一个对象:

res.set({
    "name1": "value1",
    "name2": "value2"
});

因此,您只需将

res.cookie("token", token).json(user)
替换为
res.setHeader("token", token)

您可以使用

req.headers["name"]
:

获取标题内容
jwt.verify(req.headers["token"]);
© www.soinside.com 2019 - 2024. All rights reserved.