本文介绍了Angular 4不包含HTTP请求的标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试非常简单的角度4 http请求.当我检查chrome开发人员工具时,看不到http标头.

I am trying very simple angular 4 http request.When i check chrome developer tools, i couldn't see http headers.

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();

我错过了什么吗?

推荐答案

[email protected].开始,不推荐使用@angular/http模块的所有类.现在应使用angular/common/http. 在此处阅读以了解更多信息.

Starting with [email protected]. the @angular/http module is deprecated with all its classes. Now angular/common/http should be used. Read here for more.

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();

对于较旧的版本,您可以这样做:

For the older versions, you can do it like this:

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导入正确的对象:

You have to ensure that you're importing correct objects from the @angular/http:

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

如果仍然看不到标头,则可能是所使用的服务器不允许标头.当浏览器向另一个来源发出请求时,它会发送访问控制标头请求标头,以检查服务器是否允许自定义标头.如果您的服务器未配置为允许自定义标头,则在随后的请求中将看不到它们.

If you still don't see your headers, it's also possible that the server you're using doesn't allow them. When a browser makes a request to the other origin, it sends access-control-headers-request header to check if server allows custom header. If your server is not configured to allow custom headers, you will not see them in the consequent requests.

这篇关于Angular 4不包含HTTP请求的标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:50
查看更多