Common solutions across domains

Table of contents

1: What is cross-domain

Two: Why cross-domain

Three: Cross-domain solutions

1. Proxy server

1.1. Production environment

1.2. Development environment

2.JSONP

3.CORS


1: What is cross-domain

Cross-domain means that when a browser sends a request to a server, the address of the request is different from the address of the current page, that is, at least one of the protocol, domain name, and port number is different, which causes the browser to block the page for security reasons. Interaction with requests.

 

 

Two: Why cross-domain

The emergence of cross-domain problems is caused by the browser's same-origin policy (Same-Origin Policy) . The same-origin policy is one of the most core and basic security policies of browsers. It means that browsers only allow resources with the same protocol, domain name, and port number as the current web page to interact.

The existence of the same-origin policy is for security reasons, and the purpose is to prevent malicious script attacks and ensure the security of user information. If the browser allows cross-domain access, the attacker can inject some scripts on his own website, and then induce users to automatically execute these scripts when they visit other websites, so as to achieve the purpose of attack. Therefore, the same-origin policy is one of the important measures for browsers to protect user security.

Three: Cross-domain solutions

1. Proxy server

In daily project development, the most common solution to cross-domain problems is to use a proxy server

The proxy server solves the cross-domain problem by using the same-origin policy, which is only limited to the browser's access to the server , and has no restrictions on the server's access to the server . As an intermediate server, it has a function of request forwarding.

Specifically, when the front-end webpage initiates a network request in the browser, the request is actually sent to the proxy server, and then the proxy server will forward the request to the target server, and then forward the response returned by the target server to the client .

It is worth mentioning that in the production environment and the development environment, we usually implement the proxy in different ways

1.1. Production environment

In the online environment, we generally use nginx as a reverse proxy

The following are the steps to solve cross-domain problems through Nginx reverse proxy:

1. Modify the configuration file of Nginx and add the following content in the http block:

http {
    # 允许跨域请求的地址
    add_header 'Access-Control-Allow-Origin' '*';
    
    # 允许跨域请求的方法
    add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
    
    # 允许跨域请求的请求头
    add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept, Authorization';
    
    # 允许跨域请求的请求头中可以携带的信息
    add_header 'Access-Control-Expose-Headers' 'Authorization';
    
    # 允许跨域请求携带 Cookie
    add_header 'Access-Control-Allow-Credentials' 'true';

    ...
}

2. Add the following to the server block:

server {
    listen 80;
    server_name example.com;

    # 将 /api 转发到 http://api.example.com
    location /api {
        proxy_pass http://api.example.com;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

This configuration indicates that the /api requested by the client is forwarded to http://api.example.com , and the Host and X-Real-IP in the header information requested by the client are added to the header information requested by the backend. In this way, the cross-domain problem can be solved through the Nginx reverse proxy.

The advantage of solving cross-domain problems through Nginx reverse proxy is that cross-domain requests can be managed centrally, but the disadvantage is that additional servers and maintenance costs are required.

1.2. Development environment

In the development environment, we can solve the cross-domain problem by modifying the configuration file of the local development server or adding cross-domain related code in the front-end code. Let me take the project in Vue as an example

If the project is built through the vue-cli scaffolding tool, we can set up a local server as the proxy object for the request through webpack. In the vue.config.js file, add the following code

module.exports = {
    devServer: {
        proxy: {
            '/api': { // '/api'是代理标识,用于告诉node,url前面是/api的就是使用代理的
                target: "http://xxx.xxx.xx.xx:8080", //目标地址,一般是指后台服务器地址
                changeOrigin: true, //是否跨域
                pathRewrite: { // pathRewrite 的作用是把实际Request Url中的'/api'用""代替
                    '^/api': "" 
                }
            }
        }
    }
}

2.JSONP

JSONP (JSON with Padding) is a cross-domain solution. It uses the feature that the src attribute of the script tag is not restricted by the same-origin policy. While returning JSON data from the server, it wraps the data in a callback function and returns it to Front-end, so as to achieve cross-domain requests

Here is sample code using JSONP:

function jsonp(url, callback) {
  const script = document.createElement('script');
  script.src = url + '&callback=' + callback;
  document.body.appendChild(script);
}

function handleData(data) {
  console.log(data);
}

jsonp('http://example.com/api/data?param=value', 'handleData');

In the above code, we define a jsonp function that receives a URL and the name of the callback function as parameters. Inside the function, we create a script tag and concatenate the URL and callback function name into it. Finally, add the script tag to the document, which triggers a cross-origin request.

Although JSONP can solve cross-domain problems, it also has some shortcomings , mainly including the following:

  1. Only GET requests are supported: JSONP is implemented by dynamically creating script tags, so only GET requests are supported, and POST requests and other types of requests cannot be supported.

  2. Security issues: The security issues of JSONP are relatively easy to be exploited by attackers. Attackers can modify the callback function of JSONP to inject malicious code, thus posing a security threat to the website.

  3. Unable to handle errors: Since JSONP loads data through script tags, it cannot catch request failures and cannot handle error messages.

In general, JSONP is a relatively old cross-domain solution. Although it can solve some cross-domain problems, due to the above shortcomings, other more secure and reliable cross-domain solutions are usually used in modern applications. Solutions, such as CORS, reverse proxy, etc.

3.CORS

CORS (Cross-Origin Resource Sharing, cross-domain resource sharing), which consists of a series of transmitted HTTP headers, these HTTP headers determine whether the browser prevents front-end JavaScript code from obtaining responses to cross-domain requests

CORS is very convenient to implement, you only need to add some HTTP headers so that the server can declare the allowed access sources. As long as the backend implements CORS, it realizes cross-domain

Take the koa framework as an example to add middleware and directly set the Access-Control-Allow-Origin response header

app.use(async (ctx, next)=> {
  ctx.set('Access-Control-Allow-Origin', '*');
  ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
  await next()  
})

CORS (Cross-Origin Resource Sharing) is currently a commonly used cross-domain solution. Compared with traditional cross-domain solutions such as JSONP, it has the following advantages and disadvantages:

advantage:

  1. High security: CORS is supported on both the browser side and the server side, allowing clients from different sources to request server-side resources under the premise of ensuring security, avoiding the possible security problems of JSONP.

  2. Support all types of HTTP requests: CORS not only supports cross-domain requests for simple requests (GET, POST, HEAD), but also supports complex requests (PUT, DELETE, OPTIONS, PATCH) and other types of cross-domain requests.

  3. High flexibility: CORS supports the configuration of many different types of request headers and response headers, which has higher flexibility and scalability.

  4. Compliant with the standard: CORS is a W3C standard, which is consistent with modern web development technology and can support more cross-domain scenarios.

shortcoming:

  1. Complicated configuration: The configuration of CORS is relatively complicated and requires certain settings and configurations on the server side. For some developers who are not familiar with CORS, it may take more time and effort.

  2. Compatibility issues: CORS is a part of modern web development technology. Older versions of browsers may not support it or support it incompletely, and compatibility processing is required.

  3. There is a preflight request: For some complex requests (such as requests with custom header information), the browser will send a preflight request (Preflight), which increases the overhead of the request and the burden of network transmission.

To sum up, CORS is a more secure, flexible and standard solution than traditional cross-domain solutions, but the configuration is more complicated, and issues such as compatibility and preflight requests need to be dealt with.

Guess you like

Origin blog.csdn.net/qq_42691298/article/details/129767095