javascript - 授权标头值在 SuperTest 中返回未定义
问题描述
所以我正在使用 Mocha、Supertest 和 Chai 编写测试。我所有的 API 都需要一个Authorization
可以从req.headers["authorization"]
. 这是我的测试的当前设置。
...
describe("Upload media files", () => {
it("uploads a file successfully", async () => {
const imagePath = path.join(__dirname, "../../fixtures/profile.jpeg");
const res = await app.post("/api/v1/account/upload") //app is global
.set("Authorization", "ey83hfjksksls...") //right here
.set("content-type", "multipart/form-data")
.attach("media", imagePath);
expect(res.status).to.eql(200);
expect(res.body.data).not.to.be.null;
expect(res.body.data).to.match(/https:/);
});
});
我的测试总是失败,因为由于401
某种我不知道的原因总是返回 a 。这是处理 JWT 解码的函数
async function decodeToken() {
const sessionUser = req.session.userId;
const token = req.headers["authorization"] // token value is present here.
if (!token && !sessionUser) {
return res.status(401).json({
error: "Access denied, no valid credentials.",
});
}
if (token) {
const secret = sails.config.custom.jwtSecret || process.env.JWT_SECRET;
const decoded = jwt.verify(token, secret);
req.me = decoded;
return proceed();
}
const user = await User.findOne({
id: sessionUser,
});
req.me = user;
return proceed();
}
从上面的函数中,当我对变量执行 console.log 时token
,我确实返回了一个长字符串,表明正在生成令牌并将其传递到.set('Authorization', 'eyeur9339..')
标头中,但测试仍然失败。我不知道该怎么办了。任何帮助表示赞赏,谢谢。
解决方案
如果您jwt
用于授权,Bearer
请在令牌之前使用,因此您应该编写 Bearer,如下所示:
Bearer 5d5bd7f7e35a86541686f96c9cdd72ed67f5ba223811634e0319af224164823edc2d0090d1f6c2c3b1dec842ea783c71feb443ac2d26e
对于从标头获取令牌,请执行以下操作:
const token = req.headers.authorization.split(' ')[1]
const decodedToken = jwt.verify(token, secret)
推荐阅读
- javascript - 使用 vue.js 在 tailwind ui navbar 组件中修复下拉自动打开
- mysql - 如何在mysql中选择与其他随机结果匹配的结果
- javascript - 推迟js的有效方法
- java - 获取用户对 HashMap 的输入作为键并在 Java 中打印其各自的值
- angular - 将视图路由器出口更改为侧栏
- html - 在纯 HTML 中隐藏和显示 div?
- python - TypeError: zip 参数 #1 必须支持 Python 中的迭代
- java - 对不同的数据结构使用相同的接口有什么好处?
- javascript - 即使硬编码,我的电子邮件也被强制从 .com.sg 更改为 .sg
- javascript - 使用 Google Docs API 查找表起始位置索引