amiceli
amiceli

Reputation: 445

angular2 post bad parameters

I'm developping an Angular2 application who communicates with Yandex Translate API.

I've a problem when I send a POST request with http, but it works with jQuery.ajax.

My code:

var url = "https://translate.yandex.net/api/v1.5/tr.json/translate";
    var key = "API_KEY";

    var fromTo = this.from + '-' + this.to;

    var data = {
        text: this.typedText,
        key : key,
        lang: fromTo
    };

With jQuery :

    $.ajax({
        type: "POST",
        url: url,
        data: data,
        success: $.proxy(function (data) {
            this.result = data.text;
        }, this),
        error: $.proxy(function () {
            Materialize.toast('One language is not supported by Yandex.', 3000)
        }, this),
    });

And with angular2 http.post:

    this.http.post(url, JSON.stringify(data))
        .map(res => res.text())
        .subscribe(
            data  => this.result = data.text,
            error => this.displayError('One language is not supported by Yandex.')
        );

A screenshot with diff between jQuery and http response :

enter image description here

Thanks for your help

Update 1 : change headers

var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    this.http.post(url, JSON.stringify(data), {
            headers :headers
    })
    .map(res => res.text())
    .subscribe(
        data  => this.result = data.text,
        error => this.displayError('One language is not supported by Yandex.')
    );

Upvotes: 1

Views: 604

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202176

With jQuery you use url encoded data for payload and JSON for Angular2.

You need to create your payload by hand instead of using the stringify method. Something like that:

let headers = new Headers();
headers.append('Content-type ', 'x-www-form-urlencoded');

http.post('http://...', 'key=something&text=value&lang=en',
    { headers: headers });

Hope it helps you, Thierry

Upvotes: 1

Related Questions