In the Vue 2 project, vue.config.js
the backend access address can be set through the configuration file. Here is a simple example:
- Create a new file in the project root directory
vue.config.js
(if it already exists, edit it directly). vue.config.js
Add the following to the file :
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://backend.example.com', // 设置后端接口的访问地址
changeOrigin: true,
pathRewrite: {
'^/api': '' // 将请求路径中的 '/api' 替换为空字符串
}
}
}
}
}
In the above configuration, target
the field specifies the access address of the backend interface. The proxy function is used here to /api
forward the request starting with to the specified backend address. changeOrigin
The option is set to true
means that cross-domain access is enabled.
-
Make sure that the actual access address of the backend interface
target
is consistent with the field. If you need to modify, please'http://backend.example.com'
replace with the actual backend access address. -
Save
vue.config.js
the 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/xxx
the 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/user
to 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.