Reputation: 321
Without using HttpInterceptor, I would like to send a header which contains the authorization token to my backend. Here is my attempt to do so through a Headers
object:
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
});
}
In the backend I am using this middleware function to verify the token:
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();
});
};
Here is the end point in my backend:
router.get(
"/user/getCurrentPoints",
isAuthenticated,
userCtrl.getCurrentPoints
);
The problem is I am always getting 401 error: You have to login first before you can access your lists.
Also, I get that my token is undefined, in the backend. Am I sending the token incorrectly to the backend?
Upvotes: 0
Views: 4383
Reputation: 316
Try Below code
const httpOptions = {
headers: new HttpHeaders({
'Authorization': 'Bearer ' + localStorage.getItem("token")
})
};
this.httpClientObj.get(environment.apiUrl + "/user/getCurrentPoints", httpOptions);
Upvotes: 1