【问题标题】:How to make a Google Translate API V3 simple HTTP POST request?如何制作 Google Translate API V3 简单的 HTTP POST 请求?
【发布时间】:2021-04-11 21:53:53
【问题描述】:

我知道documentation exists... 这该死的神秘和复杂,典型的过度工程。它必须更简单。

我不想使用 3rd 方库...我想要一个漂亮的 vanilla 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)}`;

【问题讨论】:

  • 如果您不使用承载,则需要删除 Authorization 标头
  • 我正在使用节点。

标签: javascript node.js http google-api


【解决方案1】:

修改点:

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

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

参考:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 2011-08-10
    • 2020-02-15
    • 2012-11-05
    • 2019-11-15
    相关资源
    最近更新 更多