Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript/Angular2 http.post doesn't set headers

I'm trying to post json from Angular2 beta 8 but the headers aren't being transmitted:

import { RequestOptions, RequestMethod, RequestHeaders, RequestOptionsArgs, Http } from 'angular2/http';

// ...
let headers = new Headers(),
    body = JSON.stringify({ identifier, password });

headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
let opts:RequestOptionsArgs = { headers: headers };

this.http.post(this.baseUrl + 'auth/login', body, opts)
    .subscribe(
         data => console.log(data),
         err => console.log(err.json().message),
         () => console.log('Authentication Complete')
    );

But the XHR call in Chrome doesn't have either of these headers. Chrome debug shows that the Content-Type header is flagged Provisional Headers are Shown and shows Content-Type:text/plain;charset=UTF-8. The header values seem to be correct though:

console.log(headers.get('Content-Type')) // => 'application/json'
console.log(headers.get('Accept'))       // => 'application/json'

The problem is that I'm pulling in RequestHeaders, but it should just be Headers. Why it didn't give me an error, I don't know.

like image 834
mikebridge Avatar asked Mar 03 '16 20:03

mikebridge


1 Answers

You need to import the Headers class like this (you forgot it in your import from angular2/http):

import {
  RequestOptions,
  RequestMethod,
  RequestHeaders,
  RequestOptionsArgs,
  Http,
  Headers // <------
} from 'angular2/http';

// ...
let headers = new Headers(),
body = JSON.stringify({ identifier, password });

See this question for more details:

  • Angular2/Http (POST) headers
like image 129
Thierry Templier Avatar answered Sep 28 '22 19:09

Thierry Templier