如何在Angular中正确设置Http Request Header 2

How to correctly set Http Request Header in Angular 2

我有一个使用 Angular 2 的 Ionic 2 应用程序,它正在向 ASP.NET Core API 服务器发送一个 Http PUT。这是我用来发送请求的方法:

public update(student: Student): Promise<Student>
{
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('authentication', `${student.token}`);

    const url = `${this.studentsUrl}`;

    return this.http
        .put(url, JSON.stringify(student), { headers: headers })
        .toPromise()
        .then(() => student)
        .catch(this.handleError);
}

我正在 headers object 上设置身份验证 key/value。

但是当我在服务器上收到这个请求时,我在 header 上找不到身份验证密钥:

如图所示,header上有很多密钥,但没有我在客户端应用程序中手动添加到header中的内容和身份验证密钥。

我做错了什么?

您在 http.put() 中请求选项的参数实际上应该是 RequestOptions 类型。尝试这样的事情:

let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('authentication', `${student.token}`);

let options = new RequestOptions({ headers: headers });
return this.http
    .put(url, JSON.stringify(student), options)

你打错了。

变化: headers.append('authentication', ${student.token});

收件人: headers.append('Authentication', student.token);

注意 Authentication 是大写的

这应该可以通过从 Angular 导入 headers 轻松解决:

import { Http, Headers } from "@angular/http";

We can do it nicely using Interceptors. You dont have to set options in all your services neither manage all your error responses, just define 2 interceptors (one to do something before sending the request to server and one to do something before sending the server's response to your service)

  1. 定义一个 AuthInterceptor class 在向服务器发送请求之前做一些事情。您可以在此 class.

    中设置 api 令牌(从 localStorage 检索它,参见步骤 4)和其他选项
  2. 定义一个 responseInterceptor class 在将服务器响应发送到您的服务 (httpClient) 之前做一些事情。您可以管理您的服务器响应,最常见的用途是检查用户的令牌是否有效(如果没有从 localStorage 清除令牌并重定向到登录)。

  3. 在您的 app.module 中从“@angular/common/http”导入 HTTP_INTERCEPTORS。然后向您的提供者添加拦截器(AuthInterceptor 和 responseInterceptor)。这样做你的应用程序将在我们所有的 httpClient 调用中考虑拦截器。

  4. 在登录 http 响应(使用 http 服务)时,将令牌保存在 本地存储。

  5. 然后将 httpClient 用于所有 apirest 服务。

你可以在我的 github 项目上查看一些好的做法 here

Angular 4 >

您可以选择手动设置 headers ,或者制作一个 HTTP 拦截器 来自动设置 header(s) 每次发出请求时。


手动

设置一个header:

http
  .post('/api/items/add', body, {
    headers: new HttpHeaders().set('Authorization', 'my-auth-token'),
  })
  .subscribe();

设置headers:

this.http
.post('api/items/add', body, {
  headers: new HttpHeaders({
    'Authorization': 'my-auth-token',
    'x-header': 'x-value'
  })
}).subscribe()

局部变量(不可变再次实例化)

let headers = new HttpHeaders().set('header-name', 'header-value');
headers = headers.set('header-name-2', 'header-value-2');

this.http
  .post('api/items/add', body, { headers: headers })
  .subscribe()

The HttpHeaders class is immutable, so every set() returns a new instance and applies the changes.

来自Angulardocs.


HTTP 拦截器

A major feature of @angular/common/http is interception, the ability to declare interceptors which sit in between your application and the backend. When your application makes a request, interceptors transform it before sending it to the server, and the interceptors can transform the response on its way back before your application sees it. This is useful for everything from authentication to logging.

来自Angulardocs.

确保在整个申请过程中使用 @angular/common/http。这样你的请求就会被拦截器捕获。

第一步,创建服务:

import * as lskeys from './../localstorage.items';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '@angular/common/http';

@Injectable()
export class HeaderInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (true) { // e.g. if token exists, otherwise use incomming request.
            return next.handle(req.clone({
                setHeaders: {
                    'AuthenticationToken': localStorage.getItem('TOKEN'),
                    'Tenant': localStorage.getItem('TENANT')
                }
            }));
        }
        else {
            return next.handle(req);
        }
    }
}

第2步,添加到你的模块中:

providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HeaderInterceptor,
      multi: true // Add this line when using multiple interceptors.
    },
    // ...
  ]

有用链接:

我们使用了这样的解决方案:

this.http.get(this.urls.order + '&list', {
        headers: {
            'Cache-Control': 'no-cache',
        }
    }).subscribe((response) => { ...

引用here

将 header 添加到单个请求的更简单和当前的方法是:

// 第 1 步

const yourHeader: HttpHeaders = new HttpHeaders({
    Authorization: 'Bearer JWT-token'
});

// POST 请求

this.http.post(url, body, { headers: yourHeader });

// GET 请求

this.http.get(url, { headers: yourHeader });