Angular 4不包含http请求的标头

Bil*_*sar 14 angular

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

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();
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?

Max*_*kyi 24

与启动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();
Run Code Online (Sandbox Code Playgroud)

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

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();
Run Code Online (Sandbox Code Playgroud)

您必须确保从以下位置导入正确的对象@angular/http:

import {Http, Headers, RequestOptions} from '@angular/http';
Run Code Online (Sandbox Code Playgroud)

如果您仍然没有看到标题,那么您使用的服务器也可能不允许它们.当浏览器向另一个源发出请求时,它会发送access-control-headers-request标头以检查服务器是否允许自定义标头.如果您的服务器未配置为允许自定义标头,则不会在后续请求中看到它们.

  • 根据[关于标题的文档](https://angular.io/api/http/Headers),该类已被弃用,建议使用[class*HttpHeaders*](https://angular.io/api/公共/ HTTP/HttpHeaders).我仍然无法使它工作(虽然我的语法太无知了)所以如果你想用非过时的类更新你的答案,那将非常感激. (3认同)

Иго*_*нюк 19

如果您使用HttpClient而不是Http,您的代码应如下所示:

login(credintials: Authenticate): Observable<any> {

    const body = {
        username: credintials.username,
        password: credintials.password,
        grant_type: 'password',
        client_id: credintials.client_id
    };
    const headers = new HttpHeaders()
        .set('Content-Type', 'application/x-www-form-urlencoded')
        .set('Authorization', 'Basic loremlorem');

    return this.http.post(`${baseUrl}/uaa/oauth/token`,
        body,
        {
            headers: headers
        }
    );
}
Run Code Online (Sandbox Code Playgroud)

如果您的参数是可选的,您应该添加这样的参数:

let params: HttpParams = new HttpParams();
if (param) {
  params = params.append( 'page', param.page );
}
Run Code Online (Sandbox Code Playgroud)

源代码如下:

/**
 * Construct a new body with an appended value for the given parameter name.
 */
append(param: string, value: string): HttpParams;
Run Code Online (Sandbox Code Playgroud)