首页 > 解决方案 > 授权标头值在 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..')标头中,但测试仍然失败。我不知道该怎么办了。任何帮助表示赞赏,谢谢。

标签: javascriptnode.jsexpressmocha.jssails.js

解决方案


如果您jwt用于授权,Bearer请在令牌之前使用,因此您应该编写 Bearer,如下所示:

Bearer 5d5bd7f7e35a86541686f96c9cdd72ed67f5ba223811634e0319af224164823edc2d0090d1f6c2c3b1dec842ea783c71feb443ac2d26e

对于从标头获取令牌,请执行以下操作:

const token = req.headers.authorization.split(' ')[1]
const decodedToken = jwt.verify(token, secret)

推荐阅读