Detailed explanation of NodeJS configuration CORS implementation process

  • 2021-10-11 17:27:32
  • OfStack

Cross-domain problems mainly focus on header

First, provide an header definition of w3c http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

Provide a detailed explanation of header provided by one netizen http://kb.cnblogs.com/page/92320/

These two are helpful to help you understand the types and functions of header, but unfortunately I can't find relevant definitions for the two header attributes related across domains.

Let me tell you directly that 1 is the allowed domain of Access-Control-Allow-Origin. 2 is the allowed header type of Access-Control-Allow-Headers

Item 1 can be directly set to * to mean arbitrary, but item 2 cannot be written like this. When testing cross-domain errors in chrome, the final code looks like this:


app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  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") res.send(200);/* Jean options Request a quick return */
  else next();
});

In addition, cors module can be used

CORS requires both browser and server support. At present, all browsers support this function, and IE browser cannot be lower than IE10.

The whole CORS communication process is automatically completed by the browser without user participation. For developers, there is no difference between CORS communication and AJAX communication with the same origin, and the code is completely 1. Once Browser 1 finds that AJAX requests cross sources, it automatically adds 1 additional header information, and sometimes an additional request, but the user will not feel it.

Therefore, the key to CORS communication is the server. As long as the server implements the CORS interface, it can communicate across sources.

The browser divides CORS requests into two categories: simple requests (simple request) and non-simple requests (not-so-simple request).

As long as the following two conditions are met at the same time, it is a simple request.

(1) The request method is one of three:

HEAD GET POST

(2) The header information of HTTP does not exceed the following fields:

Accept Accept-Language Content-Language Last-Event-ID

Content-Type: limited to 3 values application/x-www-form-urlencoded, multipart/form-data, text/plain

This is for form compatibility (form), because historically Form 1 can make cross-domain requests. The cross-domain design of AJAX is that as long as the form can be sent, AJAX can be sent directly.

If the above two conditions are not met at the same time, it is a non-simple request.


Related articles: