Home  >  Article  >  Backend Development  >  Five solutions for website cross-domain

Five solutions for website cross-domain

little bottle
little bottleforward
2019-04-30 13:50:355195browse

Because the browser uses the same-origin policy, a cross-domain request occurs. A webpage requests resources from another webpage with a different domain name/different protocol/different port. This is cross-domain. This article provides 5 ways to solve the problem of website cross-domain. Friends who are interested can take a look.

1. What is leapfrog?

  • A webpage requests resources from another webpage with a different domain name/different protocol/different port. This is cross-domain.
  • Cross-domain reason: In the current domain name request website, sending other domain names through ajax requests is not allowed by default.

2. Why does a cross-domain request occur?

  • Because the browser uses the same-origin policy

3. What is the same-origin policy?

  • The same-origin policy is a well-known security policy proposed by Netscape. All browsers that support JavaScript now use this policy. The same-origin policy is the core and most basic security function of the browser. If the same-origin policy is missing, the normal functions of the browser may be affected. It can be said that the web is built on the basis of the same-origin policy, and the browser is just an implementation of the same-origin policy.

4. Why does the browser use the same-origin policy?

  • is to ensure the security of user information and prevent malicious websites from stealing data. If the web pages do not meet the same origin requirements, they will not be able to:

    • 1. Sharing Cookies, LocalStorage, IndexDB
    • 2. Obtaining DOM
    • 3. AJAX requests cannot be sent

The non-absolute nature of the same-origin policy:

<script></script>
<img/>
<iframe/>
<link/>
<video/>
<audio/>

and other tags with src attributes can be sent from different domains Load and execute resources. Same-origin policies for other plug-ins: Third-party plug-ins loaded by browsers such as Flash, Java applet, silverlight, and Google Gears also have their own same-origin policies. However, these same-origin policies do not belong to the browser’s native same-origin policies. If there are loopholes, they may Being exploited by hackers, leaving the consequences of XSS attacks

The so-called same origin refers to: the domain name, network protocol, and port number are the same. If one of the three is different, cross-domain will occur. For example: you use a browser to open http://baidu.com, and when the browser executes the JavaScript script, it is found that the script sends a request to the http://cloud.baidu.com domain name. This The browser will report an error, which is a cross-domain error.

There are five solutions:

1. Use jsonp on the front end (not recommended)

  • When we normally request a JSON data, the server returns is a string of JSON type data, and when we use the JSONP mode to request data, the server returns an executable JavaScript code. Because the cross-domain principle of jsonp is to dynamically load the src of the script, we can only pass the parameters through the url, so the type type of jsonp can only be get. Example:
$.ajax({
    url: &#39;http://192.168.1.114/yii/demos/test.php&#39;, //不同的域
    type: &#39;GET&#39;, // jsonp模式只有GET 是合法的
    data: {
        &#39;action&#39;: &#39;aaron&#39;
    },
    dataType: &#39;jsonp&#39;, // 数据类型
    jsonp: &#39;backfunc&#39;, // 指定回调函数名,与服务器端接收的一致,并回传回来
})
  • The entire process of using JSONP mode to request data: the client sends a request and specifies an executable function name (here jQuery does the encapsulation process, automatically generates a callback function for you and takes out the data for the success attribute method) Call, instead of passing a callback handle), the server accepts the backfunc function name, and then sends the data in the form of actual parameters
  • (In the jquery source code, the implementation of jsonp is Dynamically add the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag to call the js script provided by the server. jquery will load a global function in the window object, and the function will be executed when the 3f1c4e4b6b16bbbd69b2ee476dc4f83a code is inserted. After execution, 3f1c4e4b6b16bbbd69b2ee476dc4f83a will be removed. At the same time, jquery has also optimized non-cross-domain requests. If the request is under the same domain name, it will be like a normal Ajax request. Works the same.)

2. Background Http request forwarding

  • Use HttpClinet forwarding for forwarding (this method is not recommended for simple examples)
try {
    HttpClient client = HttpClients.createDefault();            //client对象
    HttpGet get = new HttpGet("http://localhost:8080/test");    //创建get请求
    CloseableHttpResponse response = httpClient.execute(get);   //执行get请求
    String mes = EntityUtils.toString(response.getEntity());    //将返回体的信息转换为字符串
    System.out.println(mes);
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

3. Configure same-origin Cors in the background (recommended)

  • Use the following code configuration for cross-domain cross-domain on SpringBoot2.0 to perfectly solve your front-end and back-end cross-domain request problems

Use the following code configuration for cross-domain on SpringBoot2.0 to perfectly solve your front-end and back-end cross-domain request problems

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 实现基本的跨域请求
 * @author linhongcun
 *
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        /*是否允许请求带有验证信息*/
        corsConfiguration.setAllowCredentials(true);
        /*允许访问的客户端域名*/
        corsConfiguration.addAllowedOrigin("*");
        /*允许服务端访问的客户端请求头*/
        corsConfiguration.addAllowedHeader("*");
        /*允许访问的方法名,GET POST等*/
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }



}

4. Use SpringCloud gateway

  • Service gateway (zuul), also known as routing center, is used to uniformly access all API interfaces and maintain services.

  • Spring Cloud Zuul realizes automated maintenance of service instances through integration with Spring Cloud Eureka, so when using service routing configuration, we do not need to use traditional routing configuration methods To specify a specific service instance address, just use the Ant mode configuration file parameters

5、使用nginx做转发

  • 现在有两个网站想互相访问接口  在http://a.a.com:81/A中想访问 http://b.b.com:81/B 那么进行如下配置即可
  • 然后通过访问 www.my.com/A 里面即可访问 www.my.com/B
server {
        listen       80;
        server_name  www.my.com;
        location /A {
            proxy_pass  http://a.a.com:81/A;
            index  index.html index.htm;
        }
        location /B {
            proxy_pass  http://b.b.com:81/B;
            index  index.html index.htm;
        }
    }
  • 如果是两个端口想互相访问接口  在http://b.b.com:80/Api中想访问 http://b.b.com:81/Api 那么进行如下配置即可
  • 使用nginx转发机制就可以完成跨域问题
server {
        listen       80;
        server_name  b.b.com;
        location /Api {
            proxy_pass  http://b.b.com:81/Api;
            index  index.html index.htm;
        }
    }

希望本篇文章对你有所帮助。

The above is the detailed content of Five solutions for website cross-domain. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete