Solutions to cross domain and cross domain problems

Keywords: Front-end Ajax http

Cross domain

What is cross domain?

Cross domain, that is, non homologous policy requests. This means that the browser cannot execute scripts from other websites. It is caused by the browser's homology policy and is a security restriction imposed by the browser.

The so-called homology means that the domain name, protocol and port are the same. It doesn't matter if you don't understand. For example:

  • Call (non cross domain)
  • Call (different primary domain names: 123 / 456, cross domain)
  • Call (different subdomains: abc/def, cross domain)
  • Call (different ports: 8080 / 8081, cross domain)
  • Call (different protocols: http/https, cross domain)

Note: Although both localhost and point to the local machine, they also belong to cross domain.

When the browser executes a javascript script, it will check which page the script belongs to. If it is not a homologous page, it will not be executed.

  1. Cross domain only exists on the browser side, not in other environments such as Android / IOS / node.js/python/java
  2. The cross domain request can be sent out, and the server can receive the request and return the result normally, but the result is intercepted by the browser.
  3. For security reasons, the browser must follow the same origin policy when using the XMLHttpRequest object to initiate HTTP requests. Otherwise, it is a cross domain HTTP request, which is prohibited by default. In other words, the cornerstone of browser security is the homology policy.
What is CORS?

CORS is a W3C standard. Its full name is "cross Origin resource sharing". It allows browsers to send XMLHttpRequest requests to cross source servers, thus overcoming the limitation that AJAX can only be used in the same source. It adds a special header [access control allow Origin] to the server to tell the client about the cross domain restrictions. If the browser supports CORS and determines that Origin passes, it will allow XMLHttpRequest to initiate cross domain requests.

CORS Header

Access-Control-Max-Age: 86400
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Credentials: true
Interpretation of meaning:
1. Access control allow origin Domain (self setting, here is only an example) initiates cross domain requests
2. Access control Max age is set to 86400 seconds, and no pre verification request needs to be sent
3. Access control allow methods sets the methods that allow cross domain requests
4. Access control allow headers allows cross domain requests to contain content type
5. Access control allow credentials settings allow cookies

What actions are blocked across domains?

The browser implements this homology strategy from two aspects: one is the request for the interface, and the other is the query for Dom

  1. Blocking interface requests is easier to understand, for example, using ajax from Experiment / jsonp.html page The two url ports are different, so they belong to cross domain. No 'access control allow origin' header is present on the requested resource will be reported on the console printing desk

    • It is worth saying that although the browser prohibits the user from displaying and operating the requested returned data, the browser does request it. If the server does not make restrictions, it will return data. In the network in debugging mode, you can see that the return status is 200 and the returned data can be seen
  2. Block dom fetches and operations

    For example, if iframe is embedded in a page and src is a b page with different sources, the dom in b cannot be operated in a, and there is no way to change the css style in the dom in b.

Although this restriction of the browser can not guarantee complete security, it will increase the difficulty of attack

Although the security mechanism is very good and can resist the intrusion of bad people, sometimes we need to cross domain request interface data or operate our own dom, which is also blocked by the browser, so we need to cross domain

The premise of cross domain is that you are with the server. You can control the data returned by the server, otherwise cross domain cannot be completed

How to solve cross domain problems?

1. The front-end method uses jsonp

JSONP requires the server side to support JSONP requests

The principle is that the link, href and src attributes in html are not affected by cross domain. Link can call remote css files, href can be linked to any url, the src of pictures can reference pictures at will, and the src attribute of script can introduce js files of different origin at will

  • script
  • img
  • link
  • iframe
  • ...

These tags do not have cross domain request restrictions


  url: '',
  method: 'get',
  dataType: 'jsonp', //=>A JSONP request is executed
  success: res => {


let express = require('express'),
  app = express();
app.listen(10001, _ => {

app.get('/selectViewData', (req, res) => {
  let {
    callback = Function.prototype
  } = req.query();
  let data = {
    code: 0,
    message: 'ddd'

Problem: JSONP can only handle get requests

2. Background configuration solution cross domain

The background solves cross domain problems through configuration

First, introduce dependencies in pom.xml

<!--Cross domain dependency-->

Then configure the filter in web.xml

<!--To allow cross domain access-->

Is it convenient for the front end to request data across domains?

Note that if the login detection filter is configured in the project, there may be a conflict, because if there is no login, it will jump to the login interface every time...

WebMvcConfigurer of spring boot injection rewriting method solves cross domain problems

 * @Description Cross domain configuration
 * @Author chenlinghong
 * @Date 2019/1/27 13:31
public class CORSConfig {

    public WebMvcConfigurer corsConfigurer(){
        return new WebMvcConfigurer() {
            public void addCorsMappings(CorsRegistry registry) {

3. iframe based cross domain solution (

4. The new window.postMessage method introduced in HTML5 is used to transfer data across domains

5. Cross domain resolution through CORS

CORS also needs server-side support

The basic idea behind CORS is to use custom HTTP headers to allow browsers and servers to understand each other, so as to determine whether the request or response is successful or not

First write your own filter CORSFilter

 * Created by 12143 on 2018/12/7.
public class CORSFilter extends OncePerRequestFilter {
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.addHeader("Access-Control-Allow-Origin", "");
        //response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        response.addHeader("Access-Control-Max-Age", "1800");//30 min
        filterChain.doFilter(request, response);

Note: if access control allow origin is *, all URLs are allowed to access. If it is *“ ”Only this url can be accessed. Note that if there is a port, the port should also be written
For example, it is configured , then only Data can be obtained, otherwise all 403 exceptions are reported
Then add this filter in web.xml


6. Through Nginx reverse proxy

Posted by aragon1337 on Mon, 20 Sep 2021 21:49:55 -0700