问题描述
我正在尝试使用 jwt 保护应用程序路由。我能够生成 jwt 并验证 jwt 我已经创建了中间件 authorize.js,我将其传递给 /sec > 在下面的代码中路由,但是当我尝试使用 jwt 访问受保护的路由时,它显示以下错误:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:518:11)
at ServerResponse.header (D:\Backend\NodeJs\aws_test\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (D:\Backend\NodeJs\aws_test\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (D:\Backend\NodeJs\aws_test\node_modules\express\lib\response.js:267:15)
at D:\Backend\NodeJs\aws_test\server.js:24:9
at Layer.handle [as handle_request] (D:\Backend\NodeJs\aws_test\node_modules\express\lib\router\layer.js:95:5)
at next (D:\Backend\NodeJs\aws_test\node_modules\express\lib\router\route.js:137:13)
at D:\Backend\NodeJs\aws_test\auth.js:21:20
at Object.module.exports [as verify] (D:\Backend\NodeJs\aws_test\node_modules\jsonwebtoken\verify.js:53:12)
at authorize (D:\Backend\NodeJs\aws_test\auth.js:11:13)
以下是我在 POSTMAN 中设置 jwt 的方法:
下面是我的代码:
server.js
const express = require('express');
const jwt = require('jsonwebtoken');
const authorize = require('./auth');
const chalk = require('chalk');
const app = express();
const port = 3000 || process.env.PORT;
app.get('/',(req,res) => {
res.send("Home page");
});
app.get('/jwt',res) => {
let token = jwt.sign({"body":"stuff"},"mypassphrase",{ algorithm: 'HS256'});
console.log(chalk.blue(token));
});
app.get('/sec',authorize,res) => {
res.json({"name":"Hello digi"});
});
app.listen(port,res) => {
console.log(chalk.green(`App is running at ${port}`));
});
auth.js
const fs = require('fs');
const jwt = require('jsonwebtoken');
authorize = (req,res,next) => {
if(typeof req.headers.authorization !== "undefined"){
let token = req.headers.authorization.split(" ")[1];
let key = fs.readFileSync('./private.pem','utf-8');
jwt.verify(token,key,{ algorithm: "HS256" },(err,user) => {
if (err) {
// shut them out!
res.json({ error: "Not Authorized" });
// throw new Error("Not Authorized");
}
// if the JWT is valid,allow them to hit
// the intended endpoint
return next();
});
}
else{
// No authorization header exists on the incoming
// request,return not authorized and throw a new error
res.json({ error: "No Authorization header" });
// throw new Error("Not Authorized");
}
}
module.exports = authorize;
我在上面的代码中做错了什么或需要正确的地方。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)