How to Configure vue.config.js Proxy Settings for API Calls in vue-element-admin
Add a proxy object to the devServer configuration in vue.config.js that matches your VUE_APP_BASE_API environment variable, forwards requests to your backend target, and uses pathRewrite to strip the prefix before sending.
When working with the PanJiaChen/vue-element-admin template, the frontend is pre-configured to use a mock server during development. To switch to a real backend API, you must configure the webpack dev server proxy settings. This setup allows you to maintain identical frontend code while seamlessly routing API calls to different backends during local development.
Understanding the Default API Configuration
Before modifying the proxy, you need to understand how the application constructs API URLs. The project uses a centralized Axios instance that relies on environment variables to determine the base path.
The Axios Instance and Base URL
In src/utils/request.js, the HTTP client is created with a baseURL pulled from process.env.VUE_APP_BASE_API:
// src/utils/request.js
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // Reads from environment
timeout: 5000
})
This means all API requests are automatically prefixed with whatever value is assigned to VUE_APP_BASE_API.
Development Environment Variables
The development build reads .env.development, which defines this variable as /dev-api:
# .env.development
VUE_APP_BASE_API = '/dev-api'
Consequently, a request to /user/info becomes /dev-api/user/info when sent from the browser during local development.
Configuring the devServer Proxy in vue.config.js
The webpack dev server configuration resides in vue.config.js under the devServer key. By default, this project only configures the mock server. To forward real API calls, you must add a proxy object that intercepts requests matching your base API path.
Proxy Configuration Structure
Add the following structure to your devServer configuration:
// vue.config.js
module.exports = {
devServer: {
port: 9527,
open: true,
overlay: { warnings: false, errors: true },
// Proxy configuration
proxy: {
[process.env.VUE_APP_BASE_API]: {
target: 'http://localhost:8080', // Your backend URL
changeOrigin: true,
pathRewrite: {
['^' + process.env.VUE_APP_BASE_API]: ''
}
}
},
before: require('./mock/mock-server.js')
}
}
Key Proxy Options Explained
target: The URL of your backend API server (e.g.,http://localhost:8080orhttps://api.example.com).changeOrigin: Set totrueto ensure theHostheader matches the target URL, preventing CORS errors when the backend validates origins.pathRewrite: Uses a regular expression to remove the/dev-apiprefix before forwarding. The backend receives/user/infoinstead of/dev-api/user/info.
How the Proxy Interacts with the Mock Server
The project includes a built-in mock server defined in mock/mock-server.js. This server is registered via the before hook in devServer, which runs before the proxy middleware.
When a request arrives:
- If the URL matches the proxy pattern (e.g., starts with
/dev-api), webpack-dev-server forwards it to thetargetbackend. - If the URL does not match, it falls through to the
beforehook, where the mock server handles it.
This architecture allows you to proxy specific endpoints to a real backend while continuing to use mock data for routes you haven't implemented yet.
Complete Working Example
Here is a complete, production-ready excerpt from vue.config.js showing the proxy configuration in context:
'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
function resolve(dir) {
return path.join(__dirname, dir)
}
const name = defaultSettings.title || 'vue Element Admin'
const port = process.env.port || process.env.npm_config_port || 9527
module.exports = {
publicPath: '/',
outputDir: 'dist',
assetsDir: 'static',
lintOnSave: process.env.NODE_ENV === 'development',
productionSourceMap: false,
devServer: {
port: port,
open: true,
overlay: {
warnings: false,
errors: true
},
// Proxy API calls to backend
proxy: {
[process.env.VUE_APP_BASE_API]: {
target: 'http://localhost:8080',
changeOrigin: true,
pathRewrite: {
['^' + process.env.VUE_APP_BASE_API]: ''
}
}
},
before: require('./mock/mock-server.js')
},
configureWebpack: {
name: name,
resolve: {
alias: {
'@': resolve('src')
}
}
}
}
With this configuration, any request starting with /dev-api (as defined in your .env.development file) is automatically forwarded to http://localhost:8080, while all other routes continue to be served by the mock server.
Summary
- The Axios instance in
src/utils/request.jsusesprocess.env.VUE_APP_BASE_API(default/dev-apiin.env.development) as its base URL. - To forward API calls to a real backend during development, add a
proxyobject to thedevServerconfiguration invue.config.js. - Use
pathRewriteto strip the/dev-apiprefix before forwarding requests to thetargetbackend. - Set
changeOrigin: trueto prevent CORS issues by ensuring theHostheader matches the backend URL. - The
beforehook registeringmock/mock-server.jscontinues to handle unproxied routes, allowing mixed mock and real API usage.
Frequently Asked Questions
Why do I get a 404 error after adding the proxy configuration?
If you see 404 errors after configuring the proxy, verify that your pathRewrite regular expression correctly matches process.env.VUE_APP_BASE_API. The pattern ['^' + process.env.VUE_APP_BASE_API]: '' must exactly match the value in .env.development (including the leading slash). Also ensure your backend server is actually running on the target port and listening for the rewritten paths.
Can I proxy to multiple different backend servers?
Yes. The proxy object can contain multiple entries with different keys. For example, you can proxy /dev-api to one server and /auth-api to another by adding separate property keys to the proxy object, each with its own target and pathRewrite configuration. This is useful when working with microservices or separate authentication servers.
How do I completely disable the mock server?
Remove or comment out the before: require('./mock/mock-server.js') line in the devServer configuration. Without this hook, webpack-dev-server will not register the mock middleware, and all requests will either be handled by the proxy or return 404 if no proxy matches. This is recommended when you have a complete backend implementation and no longer need mock data.
Does the proxy configuration affect the production build?
No. The devServer configuration, including the proxy object, is only used by webpack-dev-server during local development. When you run npm run build, Vue CLI generates static assets that make direct API calls to the URL defined by VUE_APP_BASE_API in your production environment file (.env.production), completely ignoring the proxy settings.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →