首页 > 解决方案 > 如何制作 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)}`;

标签: javascriptnode.jshttpgoogle-api

解决方案


修改点:

  • 不幸的是,在 Google API 中,API 密钥不能用于 POST 方法。看来这是谷歌方面目前的规范。因此,在您的情况下,需要使用访问令牌。

  • 不幸的是,我无法理解Authorization: "bearer". 如果使用访问令牌,请设置为Authorization: "Bearer ###accessToken###". BofBearer是大写字母。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);

参考:


推荐阅读