Setting Up a Vue CLI 3 Project with Axios
Create a new Vue project and install Axios:
vue create test
cd test
npm install axios
npm serve
Adding a Page with a API Request
Add a button to trigger a GET request to https://www.baidu.com/home/xman/data/tipspluslist:
<template>
<div class="hello">
<h1 @click="fetchData">Click to request API</h1>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'HelloWorld',
methods: {
fetchData() {
axios.get('/home/xman/data/tipspluslist')
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
}
}
}
</script>
Running this will cause a CORS error because the API domain differs from the frontend origin.
Solution 1: Vue CLI Proxy Configuration
Create vue.config.js at the project root (if it doesn't exist) and configure a dev server proxy:
module.exports = {
devServer: {
proxy: {
'/home': {
target: 'https://www.baidu.com',
changeOrigin: true
}
},
disableHostCheck: true
}
}
Restart the dev server after making these changes. The proxy will forward any request starting with /home to the target domain, bypassing CORS.
Solution 2: Nginx Reverse Proxy
For production deployment, configure Nginx as a reverse proxy.
- Locate and edit the Nginx configuration file (typically
nginx.confin theconfdirectory). - Add or modify a server block:
server {
listen 3003;
server_name localhost;
location / {
proxy_pass http://localhost:8081;
}
location /home {
proxy_pass https://www.baidu.com;
}
}
This configuraton maps:
http://localhost:3003→http://localhost:8081(your Vue frontend)http://localhost:3003/home→https://www.baidu.com(the target API)
- Reload Nginx:
nginx -s reload
- Open
http://localhost:3003/in the browser. The page loads correctly, and clicking the button successfully sends the API request without CORS issues.
Important Notes
- The proxy configured in
vue.config.jsonly works during development. For production, you must use a reverse proxy like Nginx. - For detailed Nginx configuration, refer to the offficial documentation or dedicated tutorials.