1

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.')
    );
amiceli
  • 437
  • 5
  • 11
  • 29

1 Answers1

1

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

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • I tried to change header but I still have same error (sse my update). – amiceli Jan 11 '16 at 16:42
  • Thank you, it works with your example. There is a way to transform my data object in string like 'key=something&other=value' ? – amiceli Jan 11 '16 at 16:47
  • 1
    You need to update the structure of your payload as well... I updated m'y answer ;-) – Thierry Templier Jan 11 '16 at 16:47
  • Perhaps you could have a look at the search attribute of the request options: https://angular.io/docs/js/latest/api/http/RequestOptions-class.html. I know that you can parameters after the ? in the url. But I don't know if it's set in the body in the case of à post request I need to test... – Thierry Templier Jan 11 '16 at 17:00