CORS cors and CORS
Implementation Principle
The basic idea behind CORS is to use a custom HTTP header to allow the browser to communicate with the server and decide whether the request or response should succeed or fail.
Verification Mechanism
For example, a simple request sent using GET or POST does not have a custom header, but the body content is text/plain. When sending this request, you need to attach an additional Origin header to it, which contains the source information (protocol, domain name, and port) of the Request page ), this allows the server to determine whether to respond based on the header information.
The following is an example of the Origin header:Origin: http://www.nczonline.net
If the server thinks this request is acceptableAccess-Control-Allow-Origin
The same source information is returned in the header (if it is a public resource, you can send "*" back).
For example:
Access-Control-Allow-Origin: http://www.nczonline.net
If the header does not exist, or the header does not match the source information, the browser rejects the request. Normally, the browser processes the request. Note that both requests and responses do not contain cookie information.
How to Set
Origin: the source information of the Request page.
Access-Control-Request-Method: Method used by the Request itself.
Access-Control-Request-Headers: (optional) custom header information. Multiple Headers are separated by commas.
The following is a request with a custom header NCZ sent using the POST method.
Origin: http://www.nczonline.netAccess-Control-Request-Method: POSTAccess-Control-Request-Headers: NCZ
After sending this request, the server can decide whether to allow this type of request. The server passes
Send the following header to communicate with the browser.
For example:
Access-Control-Allow-Origin: http://www.nczonline.netAccess-Control-Allow-Methods: POST, GETAccess-Control-Allow-Headers: NCZAccess-Control-Max-Age: 1728000
The backend usually receives various frontend requests. We generally use the following fields:
res.setHeader("Access-Control-Allow-Origin", "*");res.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");res.setHeader("X-Powered-By", '3.2.1');
The preceding section describes the meaning of setting the response header.
Copyright statement: Reprinted Original article Please note: Reprinted from: Web Front-end essence [http://blog.csdn.net/wu_xianqiang] http://blog.csdn.net/wu_xianqiang/article/details/79394588