Search code examples
c#proxyvuejs3vite

localhost Vite proxy does not work in vue 3


I am unable to get a vue proxy to work using the vite.config.ts configuration.

Note: To keep things simple I have everything running on http for now

the environment:

Vue 3 front end connecting to a c# rest api on my development machine.

The vue front end runs on http://localhost:3000 and the c# api runs on http://localhost:3001

Summary of problem

If i make a fetch call from vue to the backend using the actual host name and port this works just fine

const response = await fetch('http://localhost:3001/api/AuthenticationCookie/Login', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(loginData)

})

But if i try it using a vite proxy to the url '/go' the proxy never gets hit and vue just receives a 404.

 const response = await fetch('/go/api/AuthenticationCookie/Login', {
     method: 'POST',
     headers: {
         'Content-Type': 'application/json'
     },
     body: JSON.stringify(loginData)
 })

proxy setup in vite.config.ts

 export default defineConfig({
 server: {
        port: 3000,
        proxy: {
            '/go': {
                target: 'http://localhost:3001', // your backend url
                changeOrigin: false,
                secure: false, // Set to true if your backend uses HTTPS
                configure: (proxy, _options) => { 
                    proxy.on('error', (err, _req, _res) => {
                        console.log('proxy error', err);
                    });
                    proxy.on('proxyReq', (proxyReq, _req, _res) => {
                        console.log('proxy request to target', _req.method, _req.url);
                    })
                }
            }
        }
 },
  plugins: [
    vue(),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})

Solution

  • In your proxy set up, change

    changeOrigin: false
    

    to

    changeOrigin: true
    

    so that the Host header matches that of the target and not http://localhost:3001

    EDIT: '/go' remains part of the URL sent to the back end, meaning the URL is sent as '/go/api/AuthenticationCookie/Login'.

    Try removing it by adding:

            rewrite: (path) => path.replace(/^\/go/, '')
    

    after

      changeOrigin: true