Express Some pitfalls encountered in using CORS cross-domain resource sharing settings

October 12, 2017

express supports cross-domain middleware

  • ajax requests must be configured with withCredentials with a value of true, 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 to true 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 to true when the server-side Access-Control-Allow-Origin property can not be *, if necessary, you need to set the corresponding response headers such as req.headers.origin separately
  • IE10 and earlier versions do not support withCredentials, please use XDomainRequest.
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();
  }
}

Profile picture

Written by leon build everything from scratch You should follow them on Github