Angular2/Http(POST)头部

16

我无法在进行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中导入头文件类:

import {Headers} from 'angular2/http';

你介意创建一个 Plunkr 吗?第一个选项看起来不错,基本上应该可以工作... - eesdil
1个回答

21

我认为你正在正确使用Angular2的HTTP支持。请参考这个可工作的plunkr链接:https://plnkr.co/edit/Y777Dup3VnxHjrGSbsr3?p=preview.

可能你忘记导入Headers类。我曾经犯过这个错误,但JavaScript控制台中没有出现错误,而我试图设置的头信息并没有实际设置成功。例如,关于Content-Type头信息,我使用了text/plain而不是application/json。您可以通过在导入中注释掉Headers来模拟此问题...

以下是一个完整的可工作示例(包含导入):

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

希望能对您有所帮助, Thierry


3
谢谢指出,感觉自己好蠢,我忘记导入 'Headers' 类了。 - Angelo A

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接