基于REST的Web应用使用API密钥认证谷歌语言API时遭遇401错误求助
基于REST的Web应用使用API密钥认证谷歌语言API时遭遇401错误求助
嘿,我太懂你遇到401错误的烦躁了!咱们先揪出问题根源——你用API密钥的方式完全不对呀😅
谷歌翻译API用API密钥认证时,绝对不能把密钥放在Authorization: Bearer头里,那个格式是给OAuth 2.0令牌用的。API密钥的正确用法是要么直接拼在请求URL的参数里,要么放在X-Goog-Api-Key请求头里,二选一就行。
先看看你原代码里的问题:
function test() { const outputElement = document.getElementById('output'); const apiUrl = 'https://translation.googleapis.com/language/translate/v2'; const requestOptions = { method: 'POST', headers: { 'Authorization': 'Bearer APIKEYINSERTEDHERE', // 这里就是错误根源! 'x-goog-user-project': // 你这里还没补全参数值哦 }, // 应该还有要翻译的文本等请求体内容吧? }; }
给你两种修正方案,选哪个都行:
方案1:把API密钥放在URL参数中
function test() { const outputElement = document.getElementById('output'); const apiKey = '你的API密钥'; // 把密钥拼到URL的key参数里 const apiUrl = `https://translation.googleapis.com/language/translate/v2?key=${apiKey}`; const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-goog-user-project': '你的谷歌云项目ID' // 记得补全这个值 }, body: JSON.stringify({ q: '要翻译的文本内容', source: 'en', // 源语言,比如英语 target: 'zh-CN' // 目标语言,比如简体中文 }) }; // 发送请求并处理结果 fetch(apiUrl, requestOptions) .then(res => res.json()) .then(data => outputElement.textContent = JSON.stringify(data)) .catch(err => outputElement.textContent = `出错啦:${err.message}`); }
方案2:用X-Goog-Api-Key头传递密钥
function test() { const outputElement = document.getElementById('output'); const apiKey = '你的API密钥'; const apiUrl = 'https://translation.googleapis.com/language/translate/v2'; const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Goog-Api-Key': apiKey, // 用这个头传递API密钥 'x-goog-user-project': '你的谷歌云项目ID' }, body: JSON.stringify({ q: '要翻译的文本内容', source: 'en', target: 'zh-CN' }) }; fetch(apiUrl, requestOptions) .then(res => res.json()) .then(data => outputElement.textContent = JSON.stringify(data)) .catch(err => outputElement.textContent = `出错啦:${err.message}`); }
另外还要检查这几个关键点:
- 确认你的API密钥已经在谷歌云控制台启用了翻译API,别光创建密钥忘了开服务
- 检查密钥的限制设置,有没有绑定特定IP或HTTP referrer?如果有,要确保你的请求来源符合要求
- 确认
x-goog-user-project的项目ID和API密钥所属的谷歌云项目一致
按这个改完,应该就能解决401的问题啦!
备注:内容来源于stack exchange,提问作者Corey Jackson
相关产品推荐
相关产品推荐

