Cross domain limitation and solution of CORS

Time:2021-7-24

Cross domain limitation and solution of CORS

Cross domain understanding

Cross domain behavior is a browser behavior. A cross domain request has actually been sent to the server, and the server has also returned a message. However, when the browser receives the returned information, it finds that the information is not a homologous request and there is no restriction to allow cross domain. Therefore, when parsing the message, it shields the message and reports an error on the console.

terms of settlement

Front end solution

Use the browser to allow labelsCross domainThis feature, for exampleJOSNP, butJSONPOnly usegetMethod request data,Principle and implementation of jsonp

Back end solution

Add headers that allow cross domain Access-Control-Allow-Origin

'access control allow origin': '*' // allow cross domain requests from all sites, or set it to a specific site

CORS pre request

A non default is used in a cross domain requestMethodsContent-TypeHeadersThe browser will first initiate aOPTIONSMethod to verify whether it passes.

Methods to allow cross domain requests

By default, the browser only allows cross domain requestsGET HEAD POSTIf you need to add more methods, you need to add them on the serverAccess-Control-Allow-Methods

'access control allow methods':'delete, put' // allow cross domain requests from all sites, or set it to a specific site

Allow cross domain requestsContent-Type

The browser allows cross domain requests by defaultContent-Typeonlytext/plain multipart/form-data application/x-www-form-urlencoded

Custom request header

If a custom request header is added to the request method, if the server does not modify the corresponding headerAccess-Control-Allow-HeardsThe client will report a cross domain error

'access control allow headers':' x-test-cors' // x-test-cors is a custom request header

Access-Control-Max-AgeTime allowed for pre request

'Access-Control-Max-Age':'1000'

Pre requested within 1000sMethodsContent-TypeHeadersThere is no need to re request verification