angular - Angular2/Http (POST) headers -
i'm unable change headers when doing post request. tried couple of things:
simple class:
export class httpservice { constructor(http: http) { this._http = http; } }
i tried:
testcall() { let body = json.stringify( { "username": "test", "password": "abc123" } ) let headers = new headers(); headers.append('content-type', 'application/json'); // tried other types test if working other types, 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'); // tried other types test if working other types, 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'); } ); }
none of 2 working. didn't forget import of classes.
i'm using google chrome. check 'network' tab, request there, , says content-type text/plain.
is bug or doing wrong?
update forgot import headers class angular2/http:
import {headers} 'angular2/http';
i think you're using http support of angular2 right way. see working plunkr: https://plnkr.co/edit/y777dup3vnxhjrgsbsr3?p=preview.
perhaps, forgot import headers
class. made mistake time ago , there no error in javascript console headers tried set weren't set. example regarding content-type
header had text/plain
instead of application/json
. can reproduce in plunkr provided commenting headers
in imports...
here complete working sample (imports included):
import {component} 'angular2/core'; import {http,headers} '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 helps you, thierry
Comments
Post a Comment