Angular2 / Http(POST)标头

时间:2016-01-27 08:44:04

标签: post angular

我在执行POST请求时无法更改标头。我尝试了几件事:

简单的课程:

export class HttpService {
    constructor(http: Http) {
        this._http = http;
    }
}

我试过了:

testCall() {
    let body = JSON.stringify(
        { "username": "test", "password": "abc123" }
    )

    let headers = new Headers();
    headers.append('Content-Type', 'application/json'); // also tried other types to test if its working with other types, but no luck

    this._http.post('http://mybackend.local/api/auth', body, { 
        headers: headers 
    })
    .subscribe(
        data => { console.log(data); },
        err => { console.log(err); },
        {} => { console.log('complete'); }
    );
}

2:

testCall() {
    let body = JSON.stringify(
        { "username": "test", "password": "abc123" }
    )

    let headers = new Headers();
    headers.append('Content-Type', 'application/json'); // also tried other types to test if its working with other types, but no luck

    let options = new RequestOptions({
        headers: headers
    });

    this._http.post('http://mybackend.local/api/auth', body, options)
    .subscribe(
        data => { console.log(data); },
        err => { console.log(err); },
        {} => { console.log('complete'); }
    );
}

两者都不起作用。我没有忘记导入任何类。

我正在使用Google Chrome。所以我检查了“网络”标签,我的请求就在那里,它说我的Content-Type是text / plain。

这是一个错误还是我做错了什么?

更新 我忘了从Angular2 / http:

导入Headers类
import {Headers} from 'angular2/http';

1 个答案:

答案 0 :(得分:21)

我认为你正在以正确的方式使用Angular2的HTTP支持。看到这个工作的plunkr:https://plnkr.co/edit/Y777Dup3VnxHjrGSbsr3?p=preview

也许,您忘记导入Headers课程。我前一段时间犯了这个错误,JavaScript控制台没有错误,但我试图设置的标题实际上没有设置。例如,关于Content-Type标题,我有text/plain而不是application/json。您可以通过在导入中对Headers进行评论来在我提供给您的plunkr中重现此内容。

这是一个完整的工作样本(包括导入):

import {Component} from 'angular2/core';
import {Http,Headers} from 'angular2/http';
import 'rxjs/Rx';

@Component({
  selector: 'my-app', 
  template: `
    <div (click)="executeHttp()">
      Execute HTTP
    </div>
  `
})
export class AppComponent {
  constructor(private http:Http) {

  }

  createAuthorizationHeader(headers:Headers) {
    headers.append('Authorization', 'Basic ' +
      btoa('a20e6aca-ee83-44bc-8033-b41f3078c2b6:c199f9c8-0548-4be79655-7ef7d7bf9d20')); 
  }

  executeHttp() {
    var headers = new Headers();
    this.createAuthorizationHeader(headers);
    headers.append('Content-Type', 'application/json');

    var content = JSON.stringify({
      name: 'my name'
    });

    return this.http.post(
      'https://angular2.apispark.net/v1/companies/', content, {
        headers: headers
      }).map(res => res.json()).subscribe(
        data => { console.log(data); },
        err => { console.log(err); }
      );
  }
}

希望它可以帮到你, 亨利