繁体   English   中英

Angular - 不在 post 请求中发送标头

[英]Angular - not sending headers in the post request

我正在发帖请求,这就是我在服务中得到的

...

const headers = new HttpHeaders();
headers
    .set('Content-Type', 'application/json; charset=utf-8')
    .set('Authorization', `Bearer' ${localStorage.getItem('token')}`);

return this.http.post<InitialData>(
    `${this.baseUrl}/api/Customers/InitialData`,
    { headers: headers });

...

但我收到这个错误 -

HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Missing autorization header", url: "https://pa-prod-***......"

我究竟做错了什么?

这将是使用拦截器的好主题

  1. 创建拦截器

jwt.interceptor.ts

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';


@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with jwt token if available
        let authToken = `Bearer ${localStorage.getItem('token')}`
        
        if (authToken) {
           request = request.clone({
             setHeaders: {
                ['Authorization']: authToken
             }
          });
        }

        return next.handle(request);
    }
}

在你的app.module.ts

providers: [
    ...
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
]

现在对于所有发出的请求,如果存在身份验证令牌,它将被添加到请求中

注意:检查您是如何添加身份验证令牌的。 它有一个不应该存在的撇号'

实际上httpHeaders是不可变的。 你可以这样做:

let headers = new HttpHeaders({
  "Content-Type": "application/json; charset=utf-8",
  Authorization: `Bearer ${localStorage.getItem("token")}`
});
console.log(headers.get('Content-Type'));

然后您可以将其传递给http.post

看看这个:问题

通过以下方式创建headers -

const headers = new HttpHeaders()
    .set('Content-Type', 'application/json; charset=utf-8')
    .set('Authorization', `Bearer' ${localStorage.getItem('token')}`);

并将其用作 -

return this.http.post<InitialData>(url, payload, { headers: headers });

您的 http 后文语法错误。 您正在传递标头代替请求正文。

const headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8')
headers = headers.set('Authorization', `Bearer' ${localStorage.getItem('token')}`);

return this.http.post<InitialData>(
    `${this.baseUrl}/api/Customers/InitialData`,
    dataToPost, 
    {headers: headers}
);

您的代码中有两个主要问题:

Zam Abdul Vahid 的回答提到了第一个:您在第二个参数(即请求的正文)而不是第三个参数中提供标头。 如果你没有身体数据可以给,你可以把null作为第二个参数。

programoholic提到了第二个问题,他向您解释说 HttpHeader 是不可变的,即您不能直接修改它们, set方法将返回新填充的 object。

您在Bearer之后还有一个剩余的单引号,不需要。

所以最后,如果你做一些事情,比如链接你的set调用,下面的代码应该可以工作:

const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8').set('Authorization', `Bearer ${localStorage.getItem('token')}`);

return this.http.post<InitialData>(
    `${this.baseUrl}/api/Customers/InitialData`,
     null,
    { headers }
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM