Ionic 2 - Angular 2 http Headers are not being sen

2019-05-17 10:15发布

问题:

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.

回答1:

It's not working if you test from browser.. Please check the documentation related CORS requests.

http://blog.ionic.io/handling-cors-issues-in-ionic/



回答2:

That's what should work for you, since the second parameter for http.post is the body:

headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Bearer ' + "tokenContent");
let options = new RequestOptions({ headers: headers });

this.http.post('http://myserver/myapi', body, options)
    .map(...


回答3:

First, check if this problem is for CORS or not.

Also, try the code below:

let headers = new Headers();
headers.append('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
this.http.post(`${this.link}`,'sRequest=' + sRequest1,{ headers: headers });