1

request works fine if I send it with url with required attributes as first parameter but failed each time when trying to send with options object parameter that contains request attributes:

"use strict"
var https = require('https'),
    request = require('request');

var obj = {
    translate: function(textToTranslate) {
        var options = {
            url: "https://translate.yandex.net/api/v1.5/tr.json/translate",
            qs: {
                key: process.env.TRANSLATION_APP_TOKEN,
                lang: "en-ru",
                text: textToTranslate
            }
        }, translationRequest = https.request(options, function(response) {
            response.on('data', function (chunk) {
                console.log(JSON.parse(chunk).text[0]);
            });
        });
        console.log(options);

        translationRequest.on('error', function (response) {
            console.log(response);
        });

        translationRequest.end();
    }
};

obj.translate("hello");

I'm using qs option to pass parameters but tried formData and body but it doesn't work as well.

Thank you for any help

brandonscript
  • 68,675
  • 32
  • 163
  • 220
Alex Kamornikov
  • 278
  • 2
  • 10

1 Answers1

1

This works for me, using the request module (that you've already got loaded) instead of https. And according to the docs, you need to pass these parameters via a GET request as query params (so POST form data won't work):

"use strict"
var https = require('https'),
    request = require('request');

var obj = {
    translate: function(textToTranslate) {
        var options = {
            url: "https://translate.yandex.net/api/v1.5/tr.json/translate",
            qs: {
                key: "<redacted>",
                lang: "en-ru",
                text: textToTranslate
            }
        }
        request.get(options, function(e, r, body) {
            console.log(body);
        });
    }
};

obj.translate("hello");

Tested it against the API with a valid key, and got this response:

{"code":200,"lang":"en-ru","text":["привет"]}

For what it's worth, the reason it doesn't work like you've done it with options with the https module, is because that is the syntax designed for request not https. For https to work, you need to follow that schema:

options = {
    hostname: "translate.yandex.net",
    path: "/api/v1.5/tr.json/translate?key=" + process.env.TRANSLATION_APP_TOKEN + "&lang=en-ru&text=" + textToTranslate
}

(Docs: https://nodejs.org/api/http.html#http_http_request_options_callback)

brandonscript
  • 68,675
  • 32
  • 163
  • 220