Webpack Proxy principle and cross-domain solutions

Proxy principle 

Add a layer of intermediate server (middleware) to help send requests and receive returns.

Occurrence of cross-domain: I won’t write the details, just write why the following case will cross-domain. If port 3001 requests resources in the range of port 3000, cross-domain will occur. The occurrence of cross-domain is a problem of browsers (security policy), so configuring proxy must also be aimed at browsers.

Configuring a proxy can solve the problem because adding an intermediate server layer sends the request to the intermediate server, and the server sends it to port 3000 for you. After receiving the data returned from port 3000, the intermediate server then sends it to port 3000.

// webpack.config.js

module.exports = {
  // ...
  devServer: {
    // ...
    proxy: {
      // 代理路径匹配规则
      "/api": {
        // 代理的目标地址
        target: "http://localhost:3000",
        // 是否修改host头部
        changeOrigin: true,
        // 路径重写,将API请求重定向到代理路径的根路径下
        pathRewrite: { "^/api": "" }
      }
    }
  }
}

Solution to cross-domain:

1. Client configuration proxy 

webpack: It is the above.

Umi:    .umirc.ts or  .umirc.js add  proxy configuration items in the file. Same as webpack

Vite:   Add the following code in Vite's configuration file (vite.config.js):

export default {
  server: {
    proxy: {
      // 将指定路径的请求代理到目标地址,并添加跨域请求头
      // 请求路径是 "/api",代理到 "http://localhost:3000"
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Headers': '*'
        },
      },
    },
  },
};

2. Server configuration

Add 'Access-Control-Allow-Origin': '*' to the returned data header

devServer: {
  // ...
  headers: {
    'Access-Control-Allow-Origin': '*'
  }
}

おすすめ

転載: blog.csdn.net/weixin_43416349/article/details/130174517