search

Home  >  Q&A  >  body text

Using a proxy in vite redirects me to the proxy URL on localhost, but I specifically want to use it only for backend API calls.

This is my vite.config.ts:

import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'
import { quasar, transformAssetUrls } from '@quasar/vite-plugin'

const path = require('path');

// https://vitejs.dev/config/
export default defineConfig({
  test: {
    globals: true
  },
  plugins: [
    vue({
      template: {
        transformAssetUrls
      }
    }),
    quasar({
      sassVariables: 'src/assets/scss/quasar-variables.sass'
    })
  ],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, './src'),
    },
  },
  server: {
    proxy: {
      '/socket': {
        target: 'wss://abc-website.com:4221/',
        changeOrigin: true,
        ws: true,
        rewrite: (path) => path.replace('^/socket', ''),
      },
      '/streaming/': {
        target: 'https://abc-website.com/',
        changeOrigin: true,
      },
      '/': {
        target: 'https://abc-website.com/',
        changeOrigin: true,
        secure: false,
        ws: true
      },
    }
  }
})

Whenever my application loads, it accesses https://abc-website.com on my locahost port.

I only want to use the above url for backend api calls, for example https://abc-webite.com/api/auth.

Also, after setting the proxy in vite.config.ts, I set the baseURL to "api/".

Also, after a slight change, it calls the REST api, like https://localhost:3000/auth, where I should be https://locahost:3000/api/auth

Vite proxy doesn't seem to be working properly for me.

P粉412533525P粉412533525285 days ago581

reply all(1)I'll reply

  • P粉426780515

    P粉4267805152024-03-26 18:26:17

    I think you can do this:

    server: {
      proxy: {
        // ... your other proxies
        '/api': {
          target: 'https://abc-website.com/',
          changeOrigin: true,
          secure: false,
          ws: true,
          rewrite: (path) => path.replace(/^\/app/, ''),
        },
      }
    }

    Then all your requests to sites like localhost:3000/api/my-endpoint should be proxied to https://abc-website.com/my-endpoint . You can't proxy all "basic" requests because they are reserved for serving everything else, all assets, index.html, etc., but I'm also friendly

    reply
    0
  • Cancelreply