Using Reverse Proxy to Handle CORS Issues

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.

  1. Locate and edit the Nginx configuration file (typically nginx.conf in the conf directory).
  2. 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:3003http://localhost:8081 (your Vue frontend)
  • http://localhost:3003/homehttps://www.baidu.com (the target API)
  1. Reload Nginx:
nginx -s reload
  1. 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.js only 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.

Tags: Vue.js axios cors reverse proxy nginx

Posted on Tue, 02 Jun 2026 16:57:55 +0000 by Birch