简体   繁体   English

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

[英]How to correctly assign Headers to fetch request in Javascript

I'm quite new to more advanced APIs, and I'm trying to send a GET request to an external API using fetch, with the appropriate Headers as detailed by the API owner.我对更高级的 API 还是很陌生,我正在尝试使用 fetch 向外部 API 发送 GET 请求,并带有 API 所有者详细说明的相应标头。

However, I'm still receiving a 403 Forbidden error, and it seems that the headers are not actually being sent with the request as the Chrome DevTools shows "Provisional headers are being shown".但是,我仍然收到 403 Forbidden 错误,而且似乎标头实际上并未随请求一起发送,因为 Chrome DevTools 显示“正在显示临时标头”。

I'm using a CORS proxy: https://cors-anywhere.herokuapp.com/ , which has worked with other simpler API requests.我正在使用 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();
    })

The API request works in Postman and using curl, but with my application I receive a 403 Forbidden response. API 请求在 Postman 中工作并使用 curl,但在我的应用程序中,我收到了 403 Forbidden 响应。 As also mentioned, only provisional headers are shown in the request headers;如前所述,请求标头中仅显示临时标头; none of the headers I had set.我没有设置任何标题。

Any help would be much appreciated.任何帮助将非常感激。 Thanks!谢谢!

It looks as though you are passing an empty object as the options.看起来好像您正在传递一个空对象作为选项。 The fetch() function only takes two parameters, the resource (uri) and an object of options (see: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch ). fetch() 函数只接受两个参数, resource (uri) 和options对象(请参阅: https : //developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch )。 You have an empty object data = {} as the second parameter and your options specified as an unused, third parameter.您有一个空对象data = {}作为第二个参数,您的选项指定为未使用的第三个参数。 I believe what you want is to remove the data parameter, especially since you don't need to send a body in a GET request.我相信您想要的是删除data参数,特别是因为您不需要在 GET 请求中发送body

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();
})

The api works in Postman and curl and if you are sure you are sending all request and headers same way then it probably is CORS issue.该 api 在 Postman 和 curl 中工作,如果您确定以相同的方式发送所有请求和标头,则可能是 CORS 问题。 You have not provided enough information to truly understand if that is the case.您没有提供足够的信息来真正了解情况是否如此。

However I am trying to explain what I understand how CORS work for browsers.但是,我试图解释我所理解的 CORS 如何为浏览器工作。 Browsers before making a request (eg GET, POST, DELETE etc) makes an OPTIONS request.浏览器在发出请求(例如 GET、POST、DELETE 等)之前发出 OPTIONS 请求。 If the server that handles the request sees that the request is allowed for that host (using the origin and a few other factors), the server responds with a successful response.如果处理请求的服务器发现该主机允许该请求(使用源和其他一些因素),则服务器以成功响应进行响应。 When browsers see that the OPTIONS request is successful then the browser executes the actual request (GET, POST, DELETE, whatever).当浏览器看到 OPTIONS 请求成功时,浏览器就会执行实际的请求(GET、POST、DELETE 等等)。

Sometimes for local development you may need to overcome this as localhost will not be supported by the server.有时对于本地开发,您可能需要克服这个问题,因为服务器不支持 localhost。 In this case you can use browser extensions that intercepts your xhr requests and mocks a successful OPTIONS request for your browser and your browser thinks server responded with successful for OPTIONS call so then it allows the call.在这种情况下,您可以使用浏览器扩展来拦截您的 xhr 请求并为您的浏览器模拟成功的 OPTIONS 请求,并且您的浏览器认为服务器已成功响应 OPTIONS 调用,因此它允许调用。

Sending the headers with your request will not work.将标题与您的请求一起发送将不起作用。 The api server must allow options request to be returned with status 200 for your app to be able to make that call from browser. api 服务器必须允许返回状态为 200 的选项请求,以便您的应用程序能够从浏览器进行该调用。

All the above is based on that you sent the request from your browser the same way as from postman or curl.以上所有内容均基于您从浏览器发送请求的方式与从邮递员或 curl 发送请求的方式相同。 You can verify that if you use a network monitor app like Fiddler if you use windows.如果您使用 Windows,您可以验证是否使用像 Fiddler 这样的网络监视器应用程序。 If you are on macOS or Linux, I am not aware of a tool like Fiddler, there must be tools but as I don't work on those platform, I cannot suggest another tool to monitor network.如果你在 macOS 或 Linux 上,我不知道像 Fiddler 这样的工具,肯定有工具,但由于我不在这些平台上工作,我不能建议其他工具来监控网络。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM