Solve the problem that ajax request json type cannot pass cookies across domains

Problem Description:

In the project where the front-end and back-end are separated, the cross-domain problem has been solved, but the front-end POST request has been intercepted by login.

After investigation, it is found that this request is a POST request contentType: "application/json". This is a complex request
. Before the official POST, the browser will first issue an OPTIONS request (also called preflight), and the header will include origin and Access-Control-Request- :* and other headers, and the server response will return the corresponding The access-control-allow-origin, if it matches, then the browser will send the official POST, otherwise the above error will occur. This also answers, when accessing across domains, we clearly send the post request, if it fails, looking at the chrome network will find that it is the reason for the OPTIONS method.

front end:

var params = "{}"   
        $.ajax({
          url: "http://127.0.0.1:8810/scheduleModel/page",
          type: 'POST',
          data: params,
          async: false,
          contentType: "application/json",
          dataType: "json",
          xhrFields: {
            withCredentials: true
            },
          success:function(res){
            console.log(res)
          },
          error:function(res){
            console.log(res)
          }
        });

Backend (Java)

For such a problem, you can let go of the OPTIONS request where the login is intercepted.

 if("OPTIONS".equals(httpServletRequest.getMethod())){
    return true;
  }

OPTIONS request

The HTTP access control (CORS) OPTIONS request is designed to send a "probe" request to determine what constraints a request to a target address must have (such as what HTTP method should be used and custom request headers), and then based on its Constraints send real requests. For example, the HTTP method used for the preflight request for "cross-origin resources" is OPTIONS.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326125804&siteId=291194637