Angular2/Http (POST) headers

前端 未结 1 543
栀梦
栀梦 2020-12-03 17:07

I\'m unable to change the headers when doing a POST request. I tried a couple of things:

Simple class:

export class HttpService {
    constructor(htt         


        
相关标签:
1条回答
  • 2020-12-03 17:58

    I think you're using the HTTP support of Angular2 the right way. See this working plunkr: https://plnkr.co/edit/Y777Dup3VnxHjrGSbsr3?p=preview.

    Perhaps, you forgot to import the Headers class. I made this mistake some time ago and there was no error in the JavaScript console but the headers I tried to set weren't actually set. For example regarding the Content-Type header I had text/plain instead of application/json. You can reproduce this in the plunkr I provided to you by commenting Headers in the imports...

    Here is a complete working sample (imports included):

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

    Hope it helps you, Thierry

    0 讨论(0)
提交回复
热议问题