node.jsapi

Connect Yandex Translate API v2 to nodejs


Can anyone help with connecting Yandex Translate API v2 to nodejs. API documentation has python example. But i cant correctly translate it to nodejs

Docs https://cloud.yandex.com/en-ru/docs/translate/operations/translate

PY EXAMPLE

import requests

IAM_TOKEN = '<IAM-токен>'
folder_id = '<идентификатор каталога>'
target_language = 'ru'
texts = ["Hello", "World"]

body = {
    "targetLanguageCode": target_language,
    "texts": texts,
    "folderId": folder_id,
}

headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer {0}".format(IAM_TOKEN)
}

response = requests.post('https://translate.api.cloud.yandex.net/translate/v2/translate',
    json = body,
    headers = headers
)

print(response.text)

uncorrect NODE EXAMPLE

const axios = require("axios");

const IAM_TOKEN =
  "XXXXXXXX";
const folder_id = "XXXXXXX";
const target_language = "ru";
const texts = ["Hello"];

const json = {
  targetLanguageCode: target_language,
  texts: texts,
  folderId: folder_id,
};

const headers = {
  "Content-Type": "application/json",
  Authorization: "Bearer (IAM_TOKEN)",
};

const response = axios.post(
  "https://translate.api.cloud.yandex.net/translate/v2/translate",
  json,
  headers
);

console.log(response.text);

Big thanks if someone can help me

Codes python and node in post


Solution

  • This code will works.

    const axios = require('axios');
    
    const IAM_TOKEN = "XXXXXXXX";
    const folder_id = "YYYYY";
    const target_language = "ru";
    const texts = ["Hello"];
    const json = {
        targetLanguageCode: target_language,
        texts: texts,
        folderId: folder_id,
    };
    
    const response = axios.post(
        url = 'https://translate.api.cloud.yandex.net/translate/v2/translate',
        data = JSON.stringify(json),
        config = {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${IAM_TOKEN}`
            }
        }
    );
    // access token is 'response.data.access_token'
    console.log(JSON.stringify(response.data, null, 4));