6

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.

elixenide
  • 44,308
  • 16
  • 74
  • 100
mikebridge
  • 4,209
  • 2
  • 40
  • 50
  • Can you check this post ? probably it can solve your problem. [Angular2 How to get token by sending credentials](http://stackoverflow.com/questions/35442569/angular2-how-to-get-token-by-sending-credentials) – utnas Mar 03 '16 at 20:47
  • read this asnwer for use of `Header` http://stackoverflow.com/a/34758630/5043867 – Pardeep Jain Mar 04 '16 at 05:24

1 Answers1

15

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:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360