且构网

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

跨域ajax表单发布---如何允许?

更新时间:2023-11-27 18:36:34

如果服务器的响应标头为'Access-Control-Allow-Origin': '*'或类似内容,它将返回响应.

If the server has a response header of 'Access-Control-Allow-Origin': '*' or something similar, it will return a response.

简而言之,这与jQuery无关,与服务器无关.

在上述情况下,*是代表所有来源的通配符.但它也可以指定来源列表.

In the case above, * is a wildcard representing all origins. But it could also specify a list of origins.

请记住,即使在CORS请求中,您也可以始终将请求发送到服务器,服务器将始终接收到该请求.它只会返回一个响应,尽管它愿意(在这种情况下,它将带有访问控制标头).

Keep in mind, even in CORS requests, you can always send a request to the server, and the server will always receive it. It will only return a response though if it wants to (in this case, with the access control header, it will.)

如果服务器没有该标头,那么您将在控制台中看到常见错误,提示XMLHTTPRequest could not complete because the server does not allow cross-origin communication或它所说的任何内容.

If the server didn't have that header, then you'll get the common error in the console saying that XMLHTTPRequest could not complete because the server does not allow cross-origin communication or whatever the heck it says.

这取决于服务器使用的体系结构,但是如果它是使用Express的Node.js服务器(例如),您会看到类似的内容是server.js文件或任何地方:

It depends on the architecture the server is using, but if it's a Node.js server using Express (for example), you'd see something like this is the server.js file or wherever:

app.use(function(req, res) { res.header('Access-Control-Allow-Origin', '*') });

在不同的服务器架构(例如Apache)上,此方法将有很大的不同,但是标头被标准化为HTTP的一部分,因此该部分保持不变.

The approach would be vastly different on different sever architectures (like Apache), but the header is standardized as part of HTTP, so that part stays the same.

有关示例,请参见 AJAX跨域.