Javascript 如何使Google Translate API V3成为简单的HTTP POST请求?
我知道。。。这真是他妈的晦涩难懂,典型的过度工程。它必须更简单 我不想使用第三方库。。。我想要一杯漂亮的香草酱。 我正在用Javascript 如何使Google Translate API V3成为简单的HTTP POST请求?,javascript,node.js,http,google-api,Javascript,Node.js,Http,Google Api,我知道。。。这真是他妈的晦涩难懂,典型的过度工程。它必须更简单 我不想使用第三方库。。。我想要一杯漂亮的香草酱。 我正在用nodejs尝试以下内容 让url=`https://translation.googleapis.com/v3/projects/PROJECT_ID:translateText?key=API_KEY`; let response=等待获取(url{ 方法:“张贴”, 事实上, 证书:“包括”, 标题:{ 授权:“持票人”, “内容类型”:“应用程序/json”, },
nodejs
尝试以下内容
让url=`https://translation.googleapis.com/v3/projects/PROJECT_ID:translateText?key=API_KEY`;
let response=等待获取(url{
方法:“张贴”,
事实上,
证书:“包括”,
标题:{
授权:“持票人”,
“内容类型”:“应用程序/json”,
},
正文:{
sourceLanguageCode:“en”,
targetLanguageCode:“ru”,
内容:[“沃森博士,过来!”,
mimeType:“文本/普通”,
},
});
让result=wait response.json();
控制台日志(结果);
得到这个错误:
{ error:
{ code: 401,
message:
'Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.',
status: 'UNAUTHENTICATED' }
}
有人知道正确的调味品吗
这里有一个V2工作请求:
让url=`https://translation.googleapis.com/language/translate/v2?key=${API_KEY}&format=text&source=de&target=en&q=${encodeURIComponent(query)}`;
修改点:
- 不幸的是,在GoogleAPI中,API键不能用于POST方法。这似乎是谷歌方面目前的规范。因此,在您的情况下,需要使用访问令牌
let url = "https://translation.googleapis.com/v3/projects/PROJECT_ID:translateText"; // Modified let response = await fetch(url, { method: "POST", headers: { "Authorization": "Bearer ###accessToken###", // Modified "Content-Type": "application/json", }, body: JSON.stringify({ // Modified sourceLanguageCode: "en", targetLanguageCode: "ru", contents: ["Dr. Watson, come here!"], mimeType: "text/plain", }), }); let result = await response.json(); console.log(result);
- 不幸的是,我无法理解
。如果使用了访问令牌,请设置如下授权:“持有者”
<承载者的code>B是大写字母。请在授权:“承载人####访问令牌###”
和承载人
之间插入空格。请小心这个####访问令牌###
- 请将JSON对象作为字符串值发送
- 从您问题中的官方文档中,示例curl命令如下所示
curl -X POST \ -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \ -H "Content-Type: application/json; charset=utf-8" \ -d @request.json \ https://translation.googleapis.com/v3/projects/project-number-or-id:translateText
curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://translation.googleapis.com/v3/projects/project-number-or-id:translateText
修改脚本:
请设置您的访问令牌
let url = "https://translation.googleapis.com/v3/projects/PROJECT_ID:translateText"; // Modified
let response = await fetch(url, {
method: "POST",
headers: {
"Authorization": "Bearer ###accessToken###", // Modified
"Content-Type": "application/json",
},
body: JSON.stringify({ // Modified
sourceLanguageCode: "en",
targetLanguageCode: "ru",
contents: ["Dr. Watson, come here!"],
mimeType: "text/plain",
}),
});
let result = await response.json();
console.log(result);
参考: