簡體   English   中英

Angular2 / Http(POST)標頭

[英]Angular2/Http (POST) headers

在執行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';

我認為你正在以正確的方式使用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); }
      );
  }
}

希望它對你有幫助,蒂埃里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM