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
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));
Related
I'm trying to post a file to a remote URL using npm got. But it is not working as expected.
I have tried the following
const headers = {
"Content-Type": "image/png"
}
const requestProperties = {
method: 'POST',
url,
headers,
json: fs.createReadStream(file.path)
}
const response = await got(requestProperties);
Thank you!
Thank you #phil
I have used body property instead of json.
const headers = {
"Content-Type": "image/png"
}
const requestProperties = {
method: 'POST',
url,
headers,
body: fs.createReadStream(file.path)
}
const response = await got(requestProperties);
Without a proxy, the code works. In another Google account (cloud functions), the code works with and without a proxy. How is that possible?
Error when trying with proxy: "(node:3312) UnhandledPromiseRejectionWarning: TypeError: SocksProxyAgent is not a constructor".
const fetch = require('make-fetch-happen');
async function getSegments(appId, apiKey, proxy) {
const opts = {
headers: {
'Content-Type': 'application/json',
Authorization: `Basic ${apiKey}`
}
}
if (proxy) {
opts['proxy'] = proxy
}
const resp = await fetch(`https://onesignal.com/api/v1/apps/${appId}/segments`, opts)
const data = await resp.json()
return data.segments
}
var appId = 'abc123', apiKey = 'abc123', proxy = 'socks5://login:pass#1.2.3.4:1234';
console.log(getSegments(appId, apiKey, proxy));
I'm trying to hit a URL protected by basic auth using the snippet below.
const got = require('got');
export const getToken = async () => {
const payload = new URLSearchParams({grant_type: 'client_credentials'}).toString();
const auth = "Bearer " + Buffer.from(process.env.username + ":" + process.env.password).toString('base64');
try{
const response = await got(process.env.url, {
body: payload,
method: "POST",
headers: {
"Authorization" : auth,
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": payload.length.toString()
}
});
}catch(error){
console.log(`ERROR: ${JSON.stringify(error)}`);
}
};
But this results in an error and there are no specifics provided either.
{"name":"HTTPError","timings":{"start":1634484011218,"socket":1634484011219,"lookup":1634484011230,"connect":1634484011248,"secureConnect":1634484011288,"upload":1634484011288,"response":1634484011307,"end":1634484011310,"abort":1634484011314,"phases":{"wait":1,"dns":11,"tcp":18,"tls":40,"request":0,"firstByte":19,"download":3,"total":96}}}
Any advice on resolving the issue would be greatly appreciated. Thanks.
It's happening on got.
You need to parse the error and see what the error is. You can follow this at error.
const { HTTPError } = require('got')
const parsedError = new HTTPError(err)
console.log('---err--->', parsedError.response.body)
You will see what the exact issue is.
I've written this code in my nodeJs backend
const url = "localhost:8080/job/test/build";
const username = "admin";
const password = "116c197495ef372f129b85a8a2ca4aadc2";
const token = Buffer.from(`${username}:${password}`, "utf8").toString(
"base64"
);
const data = {
}
axios
.post(url, {
headers: {
Authorization: `Basic ${token}`,
},
})
.then((response) => res.send(response)).catch((e) => {console.log(e)});
I'm getting the following error
The same request with same credential is working in postman.
use http in url, like this"
const url = "http://localhost:8080/job/test/build";
I am trying to send a FormData containing a pdf file from a node.js script to a server. The request fail with a status code 400 in response. In the server side, it seems that he do not consider the data as a pdf file, or maybe that that the whole data is undefined.
This is what my node.js script does : (I've tried other ways to send the request but without success)
import axios from "axios"
import fs from "fs-extra"
import FormData from 'form-data'
const formData = new FormData()
const diplomaBuffer = await fs.readFile(`../data/fake/foo`+i+`.pdf`)
formData.append("diploma", diplomaBuffer)
formData.append("diplomaId", 1)
axios({
method: 'post',
processData: false,
contentType: 'multipart/form-data',
cache: false,
url: 'http://localhost:8080/certificates',
data: formData,
config: { headers: formData.getHeaders() }
})
// const response = await axios
// .post(`http://localhost:8080/certificates`, {
// body: formData
// })
// const response = await axios
// .post(`http://localhost:8080/certificates`
// , formData
// , {headers: formData.getHeaders()})
This is the function called in the server side :
app.post('/certificates', async (req, res) => {
const files = req.files
if(!files || !files.diploma || !files.diplomaId) {
res.status(400).send(new Error("No file provided"))
}
if(files.diploma.mimetype !== "application/pdf") {
res.status(400).send(new Error("diploma is not a pdf"))
}
// operations made with the received pdf (not relevant for the question)
const certificateId = uniqid()
const outputDiploma = `data/diplomas/${certificateId}.pdf`
await Promise.all([
fs.writeFile(outputDiploma, files.diploma.data),
])
await pdf.sign(outputDiploma, `${sha("sha256").update(certificateId + diplomaSecret).digest("hex")} : ${date()}`)
const diplomaBuffer = await fs.readFile(outputDiploma)
const certificate_hash = verify_pdf.hashBuffer(diplomaBuffer)
const certificateRegistry = await app.bizNetworkConnection.getAssetRegistry("consortium.supchain.assets.Certificate")
const certificate = app.factory.newResource("consortium.supchain.assets", "Certificate", certificateId)
certificate.diploma = app.factory.newRelationship("consortium.supchain.assets", "Diploma", req.body.diplomaId)
certificate.hashInfo = certificate_hash
await app.registry.certificate.add(certificate)
res.status(200).send("ok")
})