What's a CORES? Why does it give the front-end developers a headache?
Cross-Origin Resources Sharing, CORES is based on HTTP The head mechanism, which allows servers to mark areas other than itself (origin), should allow access to their own resources. For security reasons, the browser defaults to limit the cross-sources initiated from within the script. HTTP request (symmetric policy).
Common CORS reporting error scene
When you pass at the front end
fetch()
or
axios
When calling interfaces to different domain names, ports or protocols, if the backend is not properly configured CORS, the browser will throw out famous
CORS error
。 This is not an interface that is hung, but rather a browser intercepts the content of the request for privacy.
Core Command Parsing
-
Access-Control-Allow-Origin:
Core directive. Specifies which domain names are available for cross-domain access. Use wildcards
*Although convenient, it is illegal in the case of Credentials. - Access-Control-Allow-Methods: Specifies the HTTP method that cross-domain requests allow.
-
Access-Control-Allow-Headers:
If your request contains a non-simplistic head (e.g.,
AuthorizationorContent-Type: application/json) must be clearly listed here. - Access-Control-Max-Age: Tell the browser how long it will hold back the results of the pre-check request (OPTIONS) and reduce the duplicate pre-screening costs.
Address performance losses resulting from OPTIONS pre-screening request
For non-simplistic requests, the browser sends one first.
OPTIONS
(c) Detection request. By setting reasonable
Access-Control-Max-Age
, you can significantly increase the flow of interaction at the back and forth ends, avoiding the time-consuming time of each main request.
Why not recommend wildcards* in the production environment?
Use
Access-Control-Allow-Origin: *
Which means any website in the world can ask you through scripts. API。 If your interface contains user-sensitive data or requires authentication, this will be extremely significant for CSRF Risk. Professional practice is based on the request.
Origin
Dynamic judgement or clearly listed trusted domain names in the configuration file.
With our generator you can quickly get for Nginx, Apache or Express Once the industrial-level configuration template for the popular environment is ready to leave the “cross-area 502” or “OPTIONS 405”.