如何发出 Google Translate API V3 简单的 HTTP POST 请求?

Iva*_*van 5 javascript http google-api node.js

我知道文档是存在的……这真是该死的神秘和复杂,典型的过度设计。它必须更简单。

我不想使用第三方库...我想要一个漂亮的普通 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);
Run Code Online (Sandbox Code Playgroud)

并收到此错误:

{ 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' } 
}
Run Code Online (Sandbox Code Playgroud)

有谁知道正确的混合物可以实现这一目标?

这是一个 V2 工作请求:

{ 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' } 
}
Run Code Online (Sandbox Code Playgroud)

Tan*_*ike 1

修改要点:

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

  • 不幸的是,我无法理解Authorization: "bearer"。如果使用access token,请设置如下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
    
    Run Code Online (Sandbox Code Playgroud)

当以上几点反映到您的脚本中时,它会变成如下所示。

修改后的脚本:

请设置您的访问令牌。

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);
Run Code Online (Sandbox Code Playgroud)

参考: