Front-end cross-domain solution

1. What is cross-domain?

Cross-domain refers to in web development ( in the browser ), when the source of a web page is different from the source of the current page, cross-domain occurs.

The source refers to the protocol (such as HTTP), host name (such as www.example.com) and port number (such as 80). Only when these three are exactly the same, cross- domain will not occur.

The blogger would like to mention one more thing here. The best solution for cross-domain is not to cross-domain, that is, deploy the two pages to the same server (the protocol, domain name, and port number are the same)!

1.2 Cross-domain solution: CORS mechanism

CORS (Cross-Origin Resource Sharing) is a mechanism used to solve the problem of cross-domain resource access under the browser's same-origin policy restrictions. The same-origin policy requires that the browser can only send requests from the same origin (same protocol, host name, and port number), so cross-domain requests will be blocked by the browser.

CORS allows the server to specify which sources (i.e. domain names) can access its resources, thereby relaxing the restrictions of the same-origin policy to a certain extent. When the browser initiates a cross-domain request, the server can add an Access-Control-Allow-Origin field to the response header to specify the origin that is allowed to be accessed, for example:

Access-Control-Allow-Origin: https://www.example.com

In this way, requests from the https://www.example.com domain name can access the resource. If the server allows multiple sources to access resources, you can use the wildcard character (*) to specify, such as:

Access-Control-Allow-Origin: *

1.3 Cross-domain solution: proxy forwarding

If the CORS mechanism is not configured on the server and cross-domain occurs, we can use the "proxy forwarding" solution during the development phase . (development phase only)

The blogger here uses the cross-domain solution integrated in vue-cli , the official address  configuration reference | Vue CLI

In the vue.config.js configuration file of the front-end project, configure the devServer item:

module.exports = {
  devServer: {
    # ... 省略
    # 代理配置
    proxy: {
        # 如果请求地址以/api打头, 就会触发代理机制
        '/api': {
          target: 'http://localhost:3000' # 目标服务器地址
        }
      }
    }
  }
}

Pay attention to a detail here:

After configuring "proxy forwarding", the baseURL in axios can be changed from an absolute address to a relative address , and the blogger recommends you to do this, it is so convenient! Sample code:

# 绝对地址
const service = axios.create({
  baseURL: 'http://localhost:9588/api'
  ...
})
# 相对地址
# 相对当前服务器路径
const service = axios.create({
  baseURL: '/api'
  ...
})

End-------------------

Guess you like

Origin blog.csdn.net/u011690675/article/details/130362349