javascript - 如何制作 Google Translate API V3 简单的 HTTP POST 请求?
问题描述
我知道文档是存在的……它是如此的神秘和令人费解,典型的过度工程。它必须更简单。
我不想使用 3rd 方库......我想要一个漂亮的香草 js 提取。
我正在尝试以下nodejs
...
let url = `https://translation.googleapis.com/v3/projects/PROJECT_ID:translateText?key=API_KEY`;
let response = await fetch(url, {
method: "POST",
withCredentials: true,
credentials: "include",
headers: {
Authorization: "bearer",
"Content-Type": "application/json",
},
body: {
sourceLanguageCode: "en",
targetLanguageCode: "ru",
contents: ["Dr. Watson, come here!"],
mimeType: "text/plain",
},
});
let result = await response.json();
console.log(result);
并得到这个错误:
{ 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 工作请求:
let url = `https://translation.googleapis.com/language/translate/v2?key=${API_KEY}&format=text&source=de&target=en&q=${encodeURIComponent(query)}`;
解决方案
修改点:
不幸的是,在 Google API 中,API 密钥不能用于 POST 方法。看来这是谷歌方面目前的规范。因此,在您的情况下,需要使用访问令牌。
不幸的是,我无法理解
Authorization: "bearer"
. 如果使用访问令牌,请设置为Authorization: "Bearer ###accessToken###"
.B
ofBearer
是大写字母。Bearer
请在和之间插入一个空格###accessToken###
。请注意这一点。请将 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
当以上几点反映到您的脚本时,它变成如下。
修改后的脚本:
请设置您的访问令牌。
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);
参考:
推荐阅读
- docker - Dockerfile, groupadd 与 GUI 参数
- javascript - 基于屏幕位置的条件 scrollIntoView
- sas - 使用一些更正的信息和一些新信息更新数据集
- python - 如何在 django 中实现一个全局类
- c++ - 错误“'timer0_pin_port'”和“'_vector_13'”的原因是什么?
- python - 如何在 python 中构建 Web 流?
- html - 什么时候需要使用固定视口的宽度?
- r - 不合格数组 | 计算 T 平方的错误 | R
- scroll - 如何保持可滚动条的活动元素始终可见?
- python - 有没有办法使用 openpyxl 读取没有工作簿的 Excel 文件?