angular - Angular2 http.request not able to add headers -
i have code in angular2 typescript trying add headers following.
['access-token', localstorage.getitem( 'token' )], ['client', localstorage.getitem( 'client' )], ['uid', localstorage.getitem( 'email' )], ['withcredentials', 'true'], ['accept', 'application/json'], ['content-type', 'application/json' ]
while sending request can't see headers in request. working on cross domain setup. there other way it?
private _request(url: string | request, options?: requestoptionsargs) : observable<response> { let request:any; let reqopts = options || {}; let index:any; if(!reqopts.headers) { reqopts.headers = new headers(); } for( index in this._config.authheaders ) { reqopts.headers.set( this._config.authheaders[index][0], this._config.authheaders[index][1] ); } request = this.http.request(url, reqopts); return request; }
if request cross domain 1 cors concepts apply. can have @ these links more details: http://restlet.com/blog/2015/12/15/understanding-and-using-cors/ , http://restlet.com/blog/2016/09/27/how-to-fix-cors-problems/. sure, günter said, there on server side return cors headers allow browser handle response.
here sample service adds headers in http request:
export class myservice { constructor(private http:http) { } createauthorizationheader(headers:headers) { headers.append('authorization', 'basic ' + btoa('a20e6aca-ee83-44bc-8033-b41f3078c2b6:c199f9c8-0548-4be7-9655-7ef7d7bf9d33')); } getcompanies() { var headers = new headers(); this.createauthorizationheader(headers); return this.http.get('https://angular2.apispark.net/v1/companies/', { headers: headers }).map(res => res.json()); }
edit
i saw try set withcredential
header. think mix different things. withcredentials
isn't standard header there withcredentials
property on xhr javascript object. see link: https://developer.mozilla.org/en-us/docs/web/api/xmlhttprequest/withcredentials. should work without using withcredentials
custom header.
as reminder, if want use custom header, need add on server side within access-control-allow-headers
header.
hope helps you, thierry
Comments
Post a Comment