从 angular@5.x.
开始,@angular/http
模块及其所有类已被弃用。现在应该使用 angular/common/http
。请在这里了解更多。
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
this.http.post(
"http://localhost:3000/contacts",
JSON.stringify({id: 4, name: 'some'}),
httpOptions
).subscribe();
对于旧版本,您可以按照以下方式操作:
import {Http, Headers, RequestOptions} from '@angular/http';
export class AppComponent {
constructor(private http: Http) {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('authentication', `hello`);
const options = new RequestOptions({headers: headers});
this.http.post(
"http://localhost:3000/contacts",
JSON.stringify({id: 4, name: 'some'}),
options
).subscribe();
您必须确保从@angular/http
导入正确的对象:
import {Http, Headers, RequestOptions} from '@angular/http';
如果您仍然看不到您的标头,也可能是因为您使用的服务器不允许它们。当浏览器向其他来源发出请求时,它会发送 access-control-headers-request 标头来检查服务器是否允许自定义标头。如果您的服务器未配置为允许自定义标头,则将无法在随后的请求中看到它们。