Issue
I am trying to add a like on click while calling the API.
I have added a token but still in error is shows Forbidden no token provided. whereas it works fine in postman.
can’t understand why isn’t it working.
<ion-icon name="heart" class="icons" (click)="addLike(post._id)"></ion-icon>
home.module.ts
addLike(postId) {
let token = localStorage.getItem('token');
token = token.substring(1, token.length-1);
this.api.likePost(token, postId).then((res) => {
console.log("Post like API call complete");
console.log(res);
}, (err) => {
console.log("Error in API");
console.log(err);
});
}
api.service.ts
async likePost(token, postId) {
console.log("post ID "+postId);
console.log("token "+token);
let headers = new HttpHeaders({
'x-access-token': token,
});
let options = {
headers: headers
}
return await (this.http.put(environment.endpoint + "/api/v1/like-post/"+postId, options)).toPromise();
}
Solution
You are making a mistake in api.service.ts
In this.http.put the 2nd parameter is data and 3rd is options. This is the reason why it is not reading the header.
async likePost(token, postId) {
console.log("post ID "+postId);
console.log("token "+token);
let headers = new HttpHeaders({
'x-access-token': token,
});
let options = {
headers: headers
}
return await (this.http.put(environment.endpoint + "/api/v1/like-post/"+postId, options)).toPromise();
}