Cross domain

Cross-domain is when the browser intercepts the returned response, preventing data from different sources from contaminating the page.

Resolve cross-domain approaches

JSONP

By inserting a callback function after SRC in a script script, the callback parameter is the return value.

  <script>
    const callback = res= > {
      console.log(res);
    }
    function getHello() {
      const script = document.createElement('script');
      script.setAttribute("text"."text/javascript");
      script.src = 'http://localhost:8080/hello? id=1&jsoncallback=callback';
      document.body.append(script);
    }
  </script>
Copy the code

Limitations: Can only handle GET requests.

CORS (Cross-domain Resource Sharing)

HTTP header is an HTTP header based mechanism that identifies the source by the server, enabling the secure transfer of data across sources.

A simple request

HEAD, GET, POST methods and request headers in the following range

  1. Accept
  2. Accept-Language
  3. Content-Language
  4. Last-Event-ID
  5. The content-type:application/x-www-form-urlencoded,multipart/form-data,text/plain

When the browser recognizes a simple request, it automatically adds the Origin field to the request header.

If Origin is not in the range specified by the server, the response header does not have the Access-Control-Allow-Origin field and returns an error from the topmost graph.

However, the status code of the response is still 200. Our interface is successfully tuned, but the returned data is intercepted by the browser.

Add configuration on the back end

@Configuration
public class CORSConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/ * *") // Match all interface paths
                .allowedOrigins("*")
                .allowCredentials(false) // Whether cookies can be sent
                .allowedMethods("GET"."POST"."PUT"."DELETE"."OPTIONS")
                .maxAge(3600); }}Copy the code

A successful response header is returned with additional corresponding header information

Non-simple request

Send a pre-check request OPTIONS with the formal request method and request header before formal communication.

If the precheck is denied after the server check, the browser will report an error.

Once passed, it is the same as a simple request.

Proxy server