【发布时间】: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