I believe you have mastered the method after reading the case in this article , for more exciting content, please pay attention to php Chinese websiteThis time I will bring you the cross-domain solution CORS, what are the precautions for requesting the cross-domain solution CORS, the following is a practical case, let's take a look.
CORS full name Cross-Origin Resource Sharing is how to access resources across domains as defined by the HTML5 specification.
Origin indicates this domain, which is the domain of the current page of the browser. When JavaScript initiates a request to an external domain (such as sina.com), after the browser receives the response, it first checks whether
Access-Control-Allow-Origin
contains this domain. If so, Then the cross-domain request is successful. If not, the request fails and JavaScript will not be able to obtain any data in the response.Simple requests include GET, HEAD and POST (the Content-Type of POST is limited to
application/x-www-form-urlencoded
,multipart/form-data
andtext/plain
), and no custom headers can appear (for example,X-Custom: 12345
)for PUT, DELETE and others For
POST requests
of types such as application/json, before sending an AJAX request, the browser will first send anOPTIONS
request (called a preflighted request) to this URL. On, ask the target server whether to accept:The browser confirms that the
Access-Control-Allow-Methods
header of the server response does contain the Method of the AJAX request to be sent, will continue to send AJAX, otherwise, an error will be thrown##
//express后端配置:app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Credentials","true"); //服务端允许携带cookie res.header("Access-Control-Allow-Origin", req.headers.origin); //允许的访问域 res.header("Access-Control-Allow-Headers", "X-Requested-With"); //访问头 res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); //访问方法 res.header("X-Powered-By",' 3.2.1'); res.header("Content-Type", "application/json;charset=utf-8"); if (req.method == 'OPTIONS') { res.header("Access-Control-Max-Age", 86400); res.sendStatus(204); //让options请求快速返回. } else { next(); } });Copy after login
Other related articles!
Recommended reading:The above is the detailed content of Request cross-domain workaround CORS. For more information, please follow other related articles on the PHP Chinese website!