RBa*_*iak 42 http angular2-http angular
我有一个使用Angular 2的Ionic 2应用程序,它将Http PUT发送到ASP.NET Core API服务器.这是我用来发送请求的方法:
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);
}
Run Code Online (Sandbox Code Playgroud)
我在headers对象上设置了身份验证密钥/值.
但是当我在服务器上收到此请求时,我在标题上找不到身份验证密钥:
正如您在图片中看到的那样,标题上有许多键,但不是我手动添加到客户端应用程序中的标题的内容和身份验证密钥.
我究竟做错了什么?
小智 65
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)
Run Code Online (Sandbox Code Playgroud)
Bra*_*age 35
您可以选择手动设置标头,也可以创建HTTP拦截器.
Angular <4.3的先决条件:
请确保您@angular/common/http在整个应用程序中使用(在Angular 4.3中已更改).
HttpHeaders类是不可变的,因此每个set()都返回一个新实例并应用更改.
来自Angular 文档.
设置标题:
http
.post('/api/items/add', body, {
headers: new HttpHeaders().set('Authorization', 'my-auth-token'),
})
.subscribe();
Run Code Online (Sandbox Code Playgroud)
设置多个标题:
this.http
.post('api/items/add', body, {
headers: new HttpHeaders({
'Authorization': 'my-auth-token',
'x-header': 'x-value'
})
}).subscribe()
Run Code Online (Sandbox Code Playgroud)
局部变量(不可变实例化)
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()
Run Code Online (Sandbox Code Playgroud)
@ angular/common/http的一个主要特性是拦截,即声明位于应用程序和后端之间的拦截器的能力.当您的应用程序发出请求时,拦截器会在将其发送到服务器之前对其进行转换,拦截器可以在应用程序看到之前将响应转换回来.从身份验证到日志记录,这非常有用.
来自Angular 文档.
确保@angular/common/http在整个申请过程中使用.这样你的请求就会被拦截器捕获.
第1步,创建服务:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
第2步,将其添加到您的模块:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HeaderInterceptor,
multi: true // Add this line when using multiple interceptors.
},
// ...
]
Run Code Online (Sandbox Code Playgroud)
有用的链接:
| 归档时间: |
|
| 查看次数: |
104090 次 |
| 最近记录: |