调用Carbon Interface API返回401错误HTTP Token: Access denied求助
问题排查点
- 第一个错误:fetch配置的请求头属性名拼写错误。你代码里写的是
header,fetch API要求的请求头配置项是复数形式headers,这个错误导致Authorization头根本没有被附带在请求里,服务端收不到令牌自然返回401未授权。 - 第二个错误:POST请求体配置错误。fetch API没有
data这个配置项,传递请求体需要用body属性,且不能直接传递JS对象,需要用JSON.stringify()序列化为JSON字符串,同时要在请求头里补充Content-Type: application/json声明数据格式,否则服务端无法正确解析请求内容。 - 额外注意:如果修正后仍然出现跨域错误,说明该API不允许前端浏览器直接调用,你需要通过自己的后端服务代理转发请求,不要在前端代码里直接暴露API密钥,避免密钥泄露被他人盗用。
修正后代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Carbon Estimate Test</title> </head> <body> <button id="submit">submit</button> <script> document.getElementById('submit').addEventListener("click", getdata) function getdata() { fetch('https://www.carboninterface.com/api/v1/estimates', { method: 'POST', headers: { 'Authorization': 'Bearer 你的实际API密钥', 'Content-Type': 'application/json' }, body: JSON.stringify({ "type": "electricity", "electricity_unit": "mwh", "electricity_value": 42, "country": "us", "state": "ca" }) }).then(response => response.json()) .then(data => console.log(data)) .catch(error => { console.error('请求出错:', error); }); } </script> </body> </html>
内容的提问来源于stack exchange,提问作者danymarcha
相关产品推荐
相关产品推荐

