Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 ES5 - overriding Content-Type in HTTP POST header

Trying to override content type for the header, but it's still coming at text/plain. There's a way to doit with Ben Nadel's GateWayAPI, but hoping there's a solution that doesn't involve custom wrapping.

    var url = this.url;
    var body = JSON.stringify({email_login: "login", password_login: "password"});
    var headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });


    return this.http.post(url, body, {headers:headers})
        .map(function (response) {
            return response.json();
        })
        .catch(this.handleError);
like image 384
kaotik Avatar asked Feb 21 '26 13:02

kaotik


1 Answers

Request post of Http have the following signature:

post(url: string, body: any, options?: RequestOptionsArgs)

Third argument is parameter with type RequestOptionsArgs, which means you have to pass RequestOptions to it, not Headers. You also should use arrow operator (=>) instead of function. What you are looking for is something like this:

result: any;

httpPostTest() {

var url = this.url;
var body = JSON.stringify({email_login: "login", password_login: "password"});

let headers: Headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded' });
let options: RequestOptions = new RequestOptions({ headers: headers });

this.http.post(url, body, options)
    .map(response => {
        response = response.json();
    })
    .catch(this.handleError);
}

After this, you need to use subscribe to get response, so let's say that this function is called httpPostTest (I'll add it above) and we want to store response in variable called result:

this.httpPostTest().subscribe(
            response => { this.result = response; },
            error => { console.log('ERROR'); },
            () => { console.log('FINISHED')}
);
like image 165
Stefan Svrkota Avatar answered Feb 23 '26 04:02

Stefan Svrkota



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!