且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从服务器端启用CORS?

更新时间:2023-11-27 22:14:04

下面是有关其工作原理的简短尝试:浏览器是同源的实施政策和跨域限制。具体来说,浏览器会阻止前端JavaScript代码访问跨域请求的响应,除非发出请求的服务器发送请求以发送响应头 Access-Control-Allow-

Here’s an attempt at a short summary of how it works: The browser is where the same-origin policy and cross-origin restrictions are enforced. Specifically, browsers block frontend JavaScript code from being able to access responses from cross-origin requests—unless the servers the requests are made to send the response header Access-Control-Allow-Origin in responses.

换句话说,让浏览器放宽同源策略的方法是服务器使用 Access-Control-Allow-Origin 标头表示他们选择了跨域请求。

In other words, the way for getting browsers to relax the same-origin policy is for servers to use the Access-Control-Allow-Origin header to indicate they’re opting in to cross-origin requests.

因此,浏览器是应用或放宽任何跨域限制的地方。

So, browsers are the place where any cross-origin restrictions are either being applied or relaxed.

一个有助于说明其工作原理的案例是一个简单的跨域 POST 。只要跨域 POST 没有任何会触发浏览器执行 CORS预检 OPTIONS 请求,浏览器将继续执行发出请求,甚至可以跨域发送。发送 POST 的服务器将继续接受它,然后发送响应。

One case that helps to illustrate how it works is a simple cross-origin POST. As long as a cross-origin POST doesn’t have any custom request headers that will trigger browsers to do a CORS preflight OPTIONS request, a browser will go ahead and make the request, even cross-origin. And the server that POST is sent to will go ahead and accept it and then send a response.

会发生什么那么这就是来自浏览器的跨域限制的地方-因为该 POST 请求是使用XHR或Fetch API或某些JavaScript的Ajax方法从前端JavaScript代码发送的库,然后除非响应包含 Access-Control-Allow-Origin 标头,否则浏览器将不允许前端代码访问响应(即使服务器接受了 POST 并成功)。

What happens then is where the cross-origin restrictions from browsers kick in—because if that POST request was sent from frontend JavaScript code using XHR or the Fetch API or an Ajax method from some JavaScript library, then unless the response includes the Access-Control-Allow-Origin header, browsers won’t allow the frontend code to access the response (even though the server accepted the POST and it succeeded).

无论如何,我希望以上内容可以弄清楚在服务器中启用CORS支持的实际含义。

Anyway, I hope the above helps to clarify what enabling CORS support in servers actually means, and what effects it has, and that the actual policy enforcement is performed by browsers.

当然,以上所有内容仅描述了最简单的情况,没有任何特征触发浏览器执行 CORS预检 OPTIONS 请求

Of course all of the above just describes the simplest case, where there are no characteristics of the request that will trigger browsers to do a CORS preflight OPTIONS request.

但是在那种情况下,策略执行全由浏览器执行-实际上,甚至更是如此,例如,浏览器将不允许 POST 与定制标头甚至会发送给服务器,除非服务器明确指示(响应预检 OPTIONS )服务器已选择接收跨域包含该自定义标头的请求。

But still in that case, the policy enforcement is all performed by the browser—in fact even more so, in that, for example, browsers won’t allow a POST with custom headers to even be sent to a server to begin with unless the server explicitly indicates (in its response to the preflight OPTIONS) that the server has opted in to receiving cross-origin requests which include that custom header.