【问题标题】:How to send the authentication token with the header in Ionic 4?如何在 Ionic 4 中发送带有标头的身份验证令牌?
【发布时间】:2019-12-03 17:23:48
【问题描述】:

在不使用 HttpInterceptor 的情况下,我想将包含授权令牌的标头发送到我的后端。这是我通过Headers 对象尝试这样做的:

   import { Http, Headers, RequestOptions } from "@angular/http";
    getPoints() {
        var headers = new Headers();
        headers.append("Authorization", "Bearer " + localStorage.getItem("token"));
        headers.append("Content-Type", "application/json");
        return this.http.get(environment.apiUrl + "/user/getCurrentPoints", {
          headers
        });
      }

在后端我使用这个中间件函数来验证令牌:

  var isAuthenticated = function(req, res, next) {
  var token = req.headers["Authorization"];
  console.log("mytoken is " + token);
  if (!token) {
    return res.status(401).json({
      error: null,
      msg: "You have to login first before you can access your lists.",
      data: null
    });
  }
  jwt.verify(token, req.app.get("secret"), function(err, decodedToken) {
    if (err) {
      return res.status(401).json({
        error: err,
        msg: "Login timed out, please login again.",
        data: null
      });
    }
    req.decodedToken = decodedToken;
    next();
  });

};

这是我后端的终点:

router.get(
  "/user/getCurrentPoints",
   isAuthenticated,
   userCtrl.getCurrentPoints
 );

问题是我总是收到 401 错误:You have to login first before you can access your lists. 另外,我发现我的令牌在后端未定义。我是否将令牌错误地发送到后端?

【问题讨论】:

  • console.log("mytoken is " + token); 的输出是什么?此外,当您阅读像 ethis 这样的授权标头时,您还会阅读 Bearer 这个词,因此您必须从结果中删除它。
  • @jps 控制台中的输出未定义。
  • @jps 我还从标题中删除了 Bearer,但我仍然遇到同样的错误

标签: node.js angular ionic-framework jwt authorization


【解决方案1】:

试试下面的代码

const httpOptions = {
    headers: new HttpHeaders({
        'Authorization': 'Bearer ' + localStorage.getItem("token")
    })
  };
this.httpClientObj.get(environment.apiUrl + "/user/getCurrentPoints", httpOptions);

【讨论】:

  • 我认为引号没有正确关闭
  • 我是否必须删除 Bearer,因为我的后端没有拆分标头,还是自动完成?
  • 不,您必须在授权标头中使用 Bearer
  • 你可以这样做。 token = req.headers.authorization.split('Bearer')[1];
  • 令牌现在为空
猜你喜欢
  • 2016-07-05
  • 1970-01-01
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
  • 2021-08-17
  • 1970-01-01
  • 2019-02-19
  • 2021-08-13
相关资源
最近更新 更多