如何在 JavaScript 中正确分配标头以获取请求

cal*_*011 2 javascript fetch-api

我对更高级的 API 还很陌生,我正在尝试使用 fetch 向外部 API 发送 GET 请求,并使用 API 所有者详细说明的适当标头。

但是,我仍然收到 403 Forbidden 错误,并且标头实际上并未随请求一起发送,如 Chrome DevTools 显示的那样:

“正在显示临时标题”。

我正在使用 CORS 代理:https://cors-anywhere.herokuapp.com/,它可以处理其他更简单的 API 请求。

const proxy = 'https://cors-anywhere.herokuapp.com/';
const api = `${proxy}https://api-example.com`; // Obfuscated


// Generate the data
fetch(api, data = {}, {
    credentials: "include",
    method: "GET",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Authorization: "Bearer eLrw3eXlljyFRjaul5UoYZLNgpUeapbXSFKmLc5SVaBgv8azUtoKn7B062PjbYoS",
      "User-Agent": "any-name"
    },
    body: JSON.stringify(data)
})
    .then(response => {
        return response.text();
    })
Run Code Online (Sandbox Code Playgroud)

API 请求在 Postman 中工作并使用curl,但在我的应用程序中,我收到 403 Forbidden 响应。正如还提到的,请求标头中仅显示临时标头;我没有设置任何标题。

任何帮助将非常感激。

Ed *_*cas 6

看起来好像您正在传递一个空对象作为选项。fetch() 函数仅接受两个参数,即resource(uri) 和对象options(请参阅: https: //developer.mozilla.org/en-US/docs/Web/API/fetch)。您有一个空对象data = {}作为第二个参数,并且您的选项指定为未使用的第三个参数。我相信您想要的是删除该data参数,特别是因为您不需要body在 GET 请求中发送 a 。

fetch(api, {
    credentials: "include",
    method: "GET",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      Authorization: "Bearer eLrw3eXlljyFRjaul5UoYZLNgpUeapbXSFKmLc5SVaBgv8azUtoKn7B062PjbYoS",
      "User-Agent": "any-name"
    }
})
.then(response => {
    return response.text();
})
Run Code Online (Sandbox Code Playgroud)