Home:ALL Converter>Ionic 2 - Angular 2 http Headers are not being sent along with the request

Ionic 2 - Angular 2 http Headers are not being sent along with the request

Ask Time:2016-07-11T15:59:42         Author:Bala Abhinav

Json Formatter

I am working in the latest beta release of Ionic and I have done a http post method to my api server. But the headers are not being sent along with the request. The code that i have used is as below : ** Ionic version - Beta-8 & Angular version -rc.3

import {Page,App,NavParams} from 'ionic-angular';
import {Headers, Http, RequestOptions} from '@angular/http';
import {Component} from '@angular/core';
import 'rxjs/add/operator/map';

@Component({
    templateUrl : 'build/pages/xyz/xyz.html'
})

export class Xyz{

    form:any;
    token:any;
    constructor(public app:App, navParams:NavParams, public http:Http){

        let code = {abc : 'abc'};
        let headers = new Headers();
        let body = JSON.stringify(code);
        headers.append('Content-Type', 'application/json');
        headers.append('Authorization', 'Bearer ' + "tokenContent");
        let options =new RequestOptions({headers : headers, body:body});
        this.http.post('http://myserver/myapi', options)
            .map(res => res.json())
            .subscribe(
                data=>{
                    console.log(data.message);
                },
                err=>{
                    console.log(err);
                },
                ()=>{
                    console.log("Process Complete");
                }
            );

When I look at console.log both options object and headers, the headers are set properly. But when I make the http request both the headers and body is not being sent when I enclose them in the options object. But when I try to send the body alone I am able to see it in the request payload.

Author:Bala Abhinav,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/38301878/ionic-2-angular-2-http-headers-are-not-being-sent-along-with-the-request
Maximilian Riegler :

That's what should work for you, since the second parameter for http.post is the body:\n\nheaders.append('Content-Type', 'application/json');\nheaders.append('Authorization', 'Bearer ' + \"tokenContent\");\nlet options = new RequestOptions({ headers: headers });\n\nthis.http.post('http://myserver/myapi', body, options)\n .map(...\n",
2016-07-11T08:26:09
marius :

It's not working if you test from browser.. Please check the documentation related CORS requests.\n\nhttp://blog.ionic.io/handling-cors-issues-in-ionic/",
2016-07-11T08:18:29
yy