search
HomeBackend DevelopmentPHP TutorialFive solutions for website cross-domain

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 / alt="Five solutions for website cross-domain" >
<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:

  • 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 <script></script> 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 <script></script> code is inserted. After execution, <script></script> 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();
}
  • 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:博客园. If there is any infringement, please contact admin@php.cn delete
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software