【问题标题】:Authorization header value returns undefined in SuperTest授权标头值在 SuperTest 中返回未定义
【发布时间】:2021-01-27 22:05:53
【问题描述】:

所以我正在使用 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 总是由于某种我不知道的原因返回。这是处理 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();
}

从上面的函数中,当我对token 变量执行console.log 时,我确实返回了一个长字符串,表明正在生成令牌并传递到.set('Authorization', 'eyeur9339..') 标头,但测试仍然失败。我不知道该怎么办了。任何帮助表示赞赏,谢谢。

【问题讨论】:

    标签: javascript node.js express mocha.js sails.js


    【解决方案1】:

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

    Bearer 5d5bd7f7e35a86541686f96c9cdd72ed67f5ba223811634e0319af224164823edc2d0090d1f6c2c3b1dec842ea783c71feb443ac2d26e
    

    为了从标头获取令牌,请这样做:

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

    【讨论】:

      猜你喜欢
      • 2017-07-23
      • 2017-11-23
      • 2011-12-09
      • 2020-09-25
      • 1970-01-01
      • 2018-12-07
      • 2021-11-21
      • 2011-04-07
      • 1970-01-01
      相关资源
      最近更新 更多