英文:
How to modify response headers without using a third party app
问题
我想从siteB向siteA发起一个简单的fetch请求,但由于CORS策略的限制而被阻止。
```javascript
fetch(siteA, {
credentials: "include",
headers: {
'Access-Control-Allow-Origin': siteB,
'Access-Control-Allow-Credentials': 'true'}
})
错误信息:
跨源资源共享(CORS)策略阻止了从origin siteB向siteA发起的fetch请求:对预检请求的响应未通过访问控制检查,不允许重定向预检请求。
然而,如果我使用一个名为Requestly的Chrome扩展,我可以使这个fetch调用正常工作,该扩展允许我更改响应标头,如下所示:
'Access-Control-Allow-Origin': siteB,
'Access-Control-Allow-Credentials': 'true'
我想知道是否有可能在不使用Requestly或任何其他第三方扩展/应用的情况下,对响应标头进行相同的更改。
谢谢
<details>
<summary>英文:</summary>
I want to make a simple fetch request to *siteA* from siteB, but I am blocked by CORS policy.
fetch(siteA, {
credentials: "include",
headers: {
'Access-Control-Allow-Origin': siteB,
'Access-Control-Allow-Credentials': 'true'`}
})
error:
>Access to fetch at *siteA* from origin *siteB* has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
However, I was able to get this fetch call to work if I use a chrome extension called Requestly, which allows me to change Response headers so that
'Access-Control-Allow-Origin': siteB,
'Access-Control-Allow-Credentials': 'true'
I am wondering if it is possible to apply the same change to the response headers like how Requestly did it, without using Requestly or any other third-party extension/app.
thank you
</details>
# 答案1
**得分**: 1
你正在尝试做的事情正是CORS(跨源资源共享)所阻止的。
> 简而言之,浏览器不会允许来自siteB服务器的任何响应在siteA上显示,除非siteB的服务器允许它。这个许可是作为预检请求的响应头部给出的。
正如你所说,你可以依赖浏览器扩展,比如[Requestly](https://requestly.io),来操纵CORS头部,或者使用像[CORS-Anywhere](https://github.com/Rob--W/cors-anywhere)这样的第三方托管服务,它会反向代理请求。
PS - CORS-Anywhere托管服务严格用于开发目的,或者你可以获取GitHub上的代码并部署到你自己的服务器上。请参考[这个][1] Stack Overflow 帖子,了解如何使用CORS Anywhere。
[1]: https://stackoverflow.com/questions/29670703/how-to-use-cors-anywhere-to-reverse-proxy-and-add-cors-headers
<details>
<summary>英文:</summary>
What you're trying to do is exactly what CORS prevents.
> In simple words, Browsers won't allow any response from siteB's server on siteA unless siteB's server gives permission for it. This permission is given as response headers on preflight request.
As you said, you can either rely on browser extensions like [Requestly](https://requestly.io) to manipulate CORS headers or use a third-party hosted service like [CORS-Anywhere](https://github.com/Rob--W/cors-anywhere) that does reverse proxy the request.
PS - CORS-Anywhere hosted service is strict to be used only for development reasons or you can take the GitHub code and deploy it on your servers. Refer [this][1] SO Post on how to use CORS Anywhere.
[1]: https://stackoverflow.com/questions/29670703/how-to-use-cors-anywhere-to-reverse-proxy-and-add-cors-headers
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论