Angular 4 不包含 http 请求的 header

标签 angular

我正在尝试非常简单的 Angular 4 http 请求。 当我检查 chrome 开发者工具时,我看不到 http header 。

const headers: Headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Bearer: 123213');
this.http.post('https://127.0.0.1:502', JSON.stringify(token), {headers: headers}).subscribe();

我错过了什么吗?

最佳答案

angular@5.x. 开始,@angular/http 模块及其所有类都已弃用。现在应该使用 angular/common/http 了。 Read here 更多信息。

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 header 以检查服务器是否允许自定义 header 。如果您的服务器未配置为允许自定义 header ,您将不会在后续请求中看到它们。

关于Angular 4 不包含 http 请求的 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44739745/

相关文章:

angular - 将数据从 Guard 传递到组件

angular - 如何在Angular 8中显示超时错误

angular - md-table - 如何更新列宽

javascript - 按向下或向上箭头键仅突出显示过滤的项目

angular - 如何选择手动选择的选项?

angular - 从 App 组件中隐藏 header 组件

angular - ng 服务在 Windows 中不工作

ios - 为什么这个页面加载速度像 iframe 一样慢,但直接访问时正常?

javascript - 在 Typescript 和 Angular2 中绑定(bind)并获取下拉列表值

angular - 仅运行一次 Angular 更改检测并停止检测该组件的更改