After creating a new Vue project, how to configure the backend access address in vue.config,js

insert image description here

In the Vue 2 project, vue.config.jsthe backend access address can be set through the configuration file. Here is a simple example:

  1. Create a new file in the project root directory vue.config.js(if it already exists, edit it directly).
  2. vue.config.jsAdd the following to the file :
module.exports = {
    
    
  devServer: {
    
    
    proxy: {
    
    
      '/api': {
    
    
        target: 'http://backend.example.com',  // 设置后端接口的访问地址
        changeOrigin: true,
        pathRewrite: {
    
    
          '^/api': ''  // 将请求路径中的 '/api' 替换为空字符串
        }
      }
    }
  }
}

In the above configuration, targetthe field specifies the access address of the backend interface. The proxy function is used here to /apiforward the request starting with to the specified backend address. changeOriginThe option is set to truemeans that cross-domain access is enabled.

  1. Make sure that the actual access address of the backend interface targetis consistent with the field. If you need to modify, please 'http://backend.example.com'replace with the actual backend access address.

  2. Save vue.config.jsthe file, and restart the Vue 2 project.

After the configuration is complete, the front-end can use the relative path when accessing the back-end interface, and /api/xxxthe proxy will forward it to the address specified by the back-end. For example, to access the backend interface http://backend.example.com/api/user, you can use in the frontend code /api/userto make a request.

Please note that the above configuration is only applicable to the development environment ( npm run serve). If you want to use this proxy configuration in a production environment, you will need to adjust your deployment and server settings accordingly.

Guess you like

Origin blog.csdn.net/weixin_53742691/article/details/131756631