简体   繁体   English

如何使用 express 在标头中发送 JWT 令牌?

[英]How send JWT token in headers using express?

I cannot redirect the page with headers.我无法重定向带有标题的页面。 I alreade used.set() and.setHeader(), but both doesn't put the token, or nother element, in header.我已经使用了.set() 和.setHeader(),但两者都没有将令牌或其他元素放入 header。 I also tried to use 'res.redirect('index', {token}), but is not work.我也尝试使用 'res.redirect('index', {token}),但不起作用。

login.js登录.js

require('dotenv').config();
const jwt = require('jsonwebtoken');
const User = require('../model/User')
const bycrypt = require('bcryptjs');

module.exports={
    async login(req, res){ 
        const { email, password } = req.body

        const userId = await User.findUserId(email)
        if(userId == '') res.status(400).send(new Error('Email invalid!'))

        const passHash = await User.passHash(userId[0].id)
        if(passHash == '')res.status(400).send(new Error('Password invalid!'))

        const passCompare = await bycrypt.compare(password, passHash[0].password)

        if(passCompare == true){
            const id = userId[0].id
            const token = jwt.sign({ id }, process.env.SECRET, {
                expiresIn: 3600
            })   >>>>>>>>this token

            return res.status(200).redirect('/index')
        }
        res.status(500).json({ message: 'Login Inválido!' })
    }
}

authenticate middleware验证中间件

require('dotenv').config();
const jwt = require('jsonwebtoken');

module.exports={
    verifyJWT(req, res, next){
        const token = req.headers['x-access-token'];
        
        if(!token) {
            return res.status(400).render('login')
        }
        jwt.verify(token, process.env.SECRET, (err, decoded) =>{
            if(err){
                console.log(err)
                return res.status(300).render('login')
            }
            req.userId = decoded.id
            next()
        })
    }
}

server.js This is the root page. server.js这是根页面。 I don't know if the problem is in the part of code.我不知道问题是否出在代码部分。

const express = require('express');
const http = require('http');
const path = require('path');
const routes = require('./routes/index');
const server = express()
const bodyParser = require('body-parser')

server.set('view engine', 'ejs')
server.set('views', path.join(__dirname, 'views'))

server.use(bodyParser.json())

server.use(express.static('public'))
server.use(express.json())
server.use(express.urlencoded({ extended: true }))
server.use('/files', express.static(path.resolve(__dirname, '..' , '..', 'tmp', 'files' )))
server.use(routes)

http.createServer(server).listen(process.env.PORT || 3000, () => {
    console.log('Rodando')
})

You can set headers on the redirect response back to the client.您可以将重定向响应的标头设置回客户端。 But if the client is a browser that is following the redirect automatically, the browser will not take the headers from your response and magically attach them to the redirected request.但是如果客户端是一个自动跟随重定向的浏览器,浏览器将不会从你的响应中获取标题并神奇地将它们附加到重定向的请求中。 Those headers will just be dropped.这些标题将被丢弃。

There are a couple ways to pass data to a redirected response via automatic redirection.有几种方法可以通过自动重定向将数据传递给重定向响应。

  1. You can put info in a queryString in the redirect URL and have your server look for it there when the redirect request comes back to your server.您可以将信息放入重定向 URL 中的 queryString 中,并在重定向请求返回到您的服务器时让您的服务器在那里查找它。

  2. You can set a cookie on the response and then that cookie will come back to your server on the redirected request.您可以在响应中设置一个 cookie,然后该 cookie 将在重定向请求时返回到您的服务器。

For a JWT token, the cookie is perhaps a better way to do things.对于 JWT 令牌,cookie 可能是更好的处理方式。


If the client for this request is your own Javascript code and it's your own Javascript that is processing and following the redirect, then your own client Javascript code can grab the custom x-access-token header and put it on the redirected request. If the client for this request is your own Javascript code and it's your own Javascript that is processing and following the redirect, then your own client Javascript code can grab the custom x-access-token header and put it on the redirected request.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM