What is cross-domain? How to solve cross-domain issues

First of all, we must first understand what is cross-domain?

  • The cross-domain problem is caused by the same-origin policy implemented by browsers for security. The same-origin policy restricts documents and scripts from different sources.
  • Cross-domain means that the browser cannot execute the scripts of other websites. It is caused by the browser's same-origin policy and is a security restriction imposed by the browser

What is homology ?

  • Same origin means that the domain name, protocol, and port number are the same

Why is there a cross-domain problem?

       Cross-domain refers to that page a wants to obtain the resources of page b, but the protocol, domain name, port, and subdomain name of page a and b are different at this time, or page a is an ip address and page b is a domain name address. Actions are cross-domain, and browsers generally restrict cross-domain access for security reasons, that is, cross-domain requests for resources are not allowed =

for example:

Domain name: The
 main domain name is different http://www.baidu.com/index.html --> http://www.sina.com/test.js The
 sub domain name is different http://www.666.baidu.com/index .html -->http://www.555.baidu.com/test.js
 domain name and domain name ip http://www.baidu.com/index.html -->http://180.149.132.47/test. js
port:
 http://www.baidu.com:8080/index.html–> http://www.baidu.com:8081/test.js
protocol:
 http://www.baidu.com:8080/index .html–> https://www.baidu.com:8080/test.js
Remarks:
    1. The port and protocol are different and can only be resolved through the background
     2. Although both localhost and 127.0.0.1 point to the local machine, they are also Cross-domain

How to solve?

Back-end solution: establish CorsConfig configuration class

@Configuration
public class CorsConfig extends WebMvcConfigurationSupport {
  
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 配置可以被跨域的路径,可以任意配置,可以具体到直接请求路径。
                .allowedMethods("*") // 允许所有的请求方法访问该跨域资源服务器,如:POST、GET、PUT、DELETE等。
                .allowedOrigins("*") // 允许所有的请求域名访问我们的跨域资源,可以固定单条或者多条内容,
                //  如:“http://www.aaa.com”,只有该域名可以访问我们的跨域资源。
                .allowedHeaders("*"); // 允许所有的请求header访问,可以自定义设置任意请求头信息。
        super.addCorsMappings(registry);
    }

The interface method of our control layer can solve cross-domain problems by adding @CrossOrigin normal front-end requests

Guess you like

Origin blog.csdn.net/qq_30631063/article/details/105937820
Recommended