CORS detailed explanation and treatment method

Keywords: Java Javascript Ajax

CORS detailed explanation and treatment method

reference resources: http://javascript.ruanyifeng.com/bom/cors.html

CORS (cross origin resource sharing): cross source resource sharing allows browsers to send XMLHttpRequest requests to from different sources, which overcomes the limitation that ajax can only be used from the same source.

Modern browsers will automatically detect whether they cross domains and complete some operations automatically. The server handles this request at the same time. Therefore, the browser side and server side need to be completed at the same time.

  • Automatically add some header information
  • Or send one more request

CORS classification

  • Simple request

    • The request methods are: HEAD, GET and POST

    • The request header fields are limited to the following (some common request headers are not listed)

      keyvalue
      Accept
      Accept-Lanuage
      Last-Event-ID
      Content-Typeapplication/x-www-form-urlencoded,multipart/form-data,text/plain
    • Note that this method corresponds to the form request. Form requests are simple requests and can cross source. This is to prevent developers from using form requests instead of ajax.

  • Complex request

1 simple request

1.1 process

1 send request (request format)

GET /cros HTTP/1.1
Origin: http://api.bob.com
Host: api.bob.com
Accept-Language: zh-CN
Connection: alive
User-Agent: Mozilla/5.0

For a simple request, the browser will send a request message with Origin, indicating the source of the request.

2 server processing

  • Return directly without processing (yes, you can return the result directly). At this time, the browser can view the result (but cannot process it), because if there is no access control allow origin field in the return request header, an exception will be thrown and caught by the onerror function of XMLHttpRequest.

  • handle

    The server adds a return header

    public Map first(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Customize-Header", "xiao");
        HashMap hashMap = new HashMap();
        hashMap.put("name", "xiaojianbiao");
        return hashMap;
    }
    
  • Other header information

keyvalueIs it necessaryeffect
Access-Contorl-Allow-Origin*, the value corresponding to Originyes
Access-Control-Allow-CredentialstruenoAllow browser to send cookie s
Access-Control-Expose-Headerscharacter stringnoAllow the browser to obtain additional header fields (otherwise only specific header fields can be obtained)

1.2 cookie handling

In addition to allowing the server to send cookies (mainly complex requests, with pre check requests), the browser should also set sending cookies (not sent by default)

  • Set the withCredentials property to true
var xHttp = new XMLHttpRequest();
xHttp.withCredentials = true;
  • Cookies still follow the same origin policy at this time, that is, cookies under different source names will not be sent to the server. In other words, although cross source access is performed, cookies will not cross source, and cookies of the same origin with the server will be uploaded.
  • Access control allow credentials must be set the same as Origin.

2 complex request

The request method is DELETE, PUT, or the content type is application/json.

2.1 process

1 send pre inspection request

Request code

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        document.getElementById("demo").innerHTML =
            this.responseText;
    }
};
xhttp.open("PUT", "http://localhost:8089/demo/demo_get.asp", true);
xhttp.setRequestHeader("Content-Type", "application/json")
xhttp.send();

Request information (pre check)

OPTIONS /demo/demo_get.asp HTTP/1.1
Host: localhost:8089
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0
Accept: */*
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: content-type
Origin: https://www.w3school.com.cn

The OPTIONS type request is accompanied by the method type (access control request method) for which the CROS request will be made, and an additional request header field (access control request headers).

2 pre inspection response

HTTP/1.1 200 
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,HEAD,POST
Access-Control-Allow-Headers: content-type
Access-Control-Max-Age: 1800
Allow: GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH
  • Access-Control-Allow-Origin
    • Allowed request sources
  • Access-Control-Allow-Methods: GET,HEAD,POST
    • Methods to allow cross source requests
  • Access-Control-Allow-Headers: content-type
    • Browser supported header fields
  • Access-Control-Max-Age: 1800
    • The validity period of this cross source request does not need to be pre checked again within this validity period. The unit is seconds.
  • Access-Control-Allow-Credentials
    • Same as above

3 cross domain processing in springboot

3.1 add code manually

Manually add the access control allow origin field of the response header.

@RequestMapping(value = "/demo/demo_get.asp")
public Map first(HttpServletRequest request, HttpServletResponse response) {
    response.addCookie(cookie);
    response.setHeader("Access-Control-Allow-Origin", "*");
    HashMap hashMap = new HashMap();
    hashMap.put("name", "xiaojianbiao");
    return hashMap;
}

Note: this method can only handle simple requests. If it is a complex request, the pre check phase will be intercepted and a 403 error will be reported.

3.2 notes

Using @ CrossOrigin annotation, this method can solve the problem of complex request 403 errors

@CrossOrigin(origins = "*")
@RequestMapping(value = "/demo/demo_get.asp")
public Map first(HttpServletRequest request, HttpServletResponse response) {
    HashMap hashMap = new HashMap();
    hashMap.put("name", "xiaojianbiao");
    return hashMap;
}

Posted by cheechm on Thu, 30 Sep 2021 17:12:14 -0700