这是我的代码:
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
Run Code Online (Sandbox Code Playgroud)
logIn(username: string, password: string) {
const url = 'http://server.com/index.php';
const body = JSON.stringify({username: username,
password: password});
const headers = new HttpHeaders();
headers.set('Content-Type', 'application/json; charset=utf-8');
this.http.post(url, body, {headers: headers}).subscribe(
(data) => {
console.log(data);
},
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log('Client-side error occured.');
} else {
console.log('Server-side error occured.');
}
}
);
}
Run Code Online (Sandbox Code Playgroud)
在这里网络调试:
Request Method:POST
Status Code:200 OK
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:46
Content-Type:text/plain …Run Code Online (Sandbox Code Playgroud) 我刚刚注意到新Interceptor中不再支持可能在先前的HTTP RequestsOption中使用的Header对象.
这是新的拦截器逻辑:
// Get the auth header from the service.
const authHeader = this.auth.getAuthorizationHeader();
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
Run Code Online (Sandbox Code Playgroud)
我现在有两种方法可以在此请求中添加标题:
例:
headers?: HttpHeaders;
headers: req.headers.set('token1', 'asd')
Run Code Online (Sandbox Code Playgroud)
setHeaders?: {
[name: string]: string | string[];
};
setHeaders: {
'token1': 'asd',
'token2': 'lol'
}
Run Code Online (Sandbox Code Playgroud)
如何在此请求中有条件地添加多个标头?与我以前使用Header对象相同:
myLovellyHeaders(headers: Headers) {
headers.set('token1', 'asd');
headers.set('token2', 'lol');
if (localStorage.getItem('token1')) {
headers.set('token3', 'gosh');
}
}
const headers = new Headers();
this.myLovellyHeaders(headers);
Run Code Online (Sandbox Code Playgroud)