express supports cross-domain middleware
- ajax requests must be configured with
withCredentials
with a value oftrue
, otherwise the request will not be made with credentials (cookies, HTTP authentication and client-side SSL certificates, etc.) - server-side receiving requests with credentials must set the response header attribute
Access-Control-Allow-Credentials
totrue
otherwise the browser will not give the response to js (response result: responseText is empty, the value of status is 0, and the onerror() event handler will be called) - When the value of
withCredentials
is set totrue
when the server-sideAccess-Control-Allow-Origin
property can not be*
, if necessary, you need to set the corresponding response headers such asreq.headers.origin
separately - IE10 and earlier versions do not support
withCredentials
, please useXDomainRequest
.
function setCORS(){
return (req, res, next) => {
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
// res.header("X-Powered-By", '3.2.1');
if (req.method === 'OPTIONS') {
return res.send('support CORS')
}
next();
}
}