[英]POST and DELETE call to the API is working in POSTMAN but not in the browser
In my Angular project, I am fetching data from the API to add users' favorite movies.在我的 Angular 项目中,我正在从 API 中获取数据以添加用户最喜欢的电影。 I have a POST method written in API, and I call that in my Angular front-end app.
我有一个用 API 编写的 POST 方法,我在我的 Angular 前端应用程序中调用它。
Here is the function in my Angular APP to fetch data from API这里是我Angular APP中的function从API取数据
public addFavMovie(id: any): Observable<any> {
const token = localStorage.getItem('token'); const username = localStorage.getItem('user');return this.http.post(apiUrl+`users/${username}/movies/${id}`, {headers: new HttpHeaders(
{
Authorization: `Bearer + ${token}`,})}).pipe(
map(this.extractResponseData),
catchError(this.handleError) );}
Following is the function to add a movie.下面是function添加电影。
addToUserFavs(id: string): void {
console.log(id);
const token = localStorage.getItem('token');
console.log(token)
this.fetchApiData.addFavMovie(id).subscribe((response: any) => {
console.log(response);
this.ngOnInit();
});
}
And following is the code in my API以下是我的 API 中的代码
app.post('/users/:Username/movies/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
var favMovie = req.params.id;
console.log(favMovie);
Users.findOneAndUpdate({ Username: req.params.Username }, {
$addToSet: { FavouriteMovies: req.params.id }
},
{ new: true },
(err, updatedUser) => {
if (err) {
console.error(err);
res.status(500).send('Error' + err);
} else {
res.json(updatedUser);
}
});
});
I cannot access this endpoint through the browser when I run the Angular project, but the endpoints work fine when I check them in POSTMAN, and I can add movies through POSTMAN. However, it's giving a 401 status code error in a browser, and the user is not authorized.当我运行 Angular 项目时,我无法通过浏览器访问这个端点,但是当我在 POSTMAN 中检查它们时,端点工作正常,我可以通过 POSTMAN 添加电影。但是,它在浏览器中给出了 401 状态代码错误,并且用户未被授权。
Do you know how to resolve this error?你知道如何解决这个错误吗? Thank you
谢谢
`Bearer + ${token}`
This is some random syntax you got there bud.这是你得到的一些随机语法。
if your token is XXX, the resulting token with this syntax will be如果您的令牌是 XXX,则使用此语法生成的令牌将是
Bearer + XXX
Change to one of either:更改为其中之一:
Authorization: 'Bearer ' + token
Authorization: `Bearer ${token}`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.