reactjsproxyvite

React - Vite Proxy Config not changing origin


I have the following in my vite.config.ts:

server: {
    proxy: {
        '/api': {
            target: 'http://localhost:10000',
            changeOrigin: true,
            secure: false,
            ws: true,
            rewrite: path => path.replace('/api', ''),
            configure: (proxy, _options) => {
                proxy.on('error', (err, _req, _res) => {
                  console.log('proxy error', err);
                });
                proxy.on('proxyReq', (proxyReq, req, _res) => {
                  console.log('Sending Request to the Target:', req.method, req.url);
                });
                proxy.on('proxyRes', (proxyRes, req, _res) => {
                  console.log('Received Response from the Target:', proxyRes.statusCode, req.url);
                });
              },
        },
    },
},

And the following API call:

import axios from 'axios';

const API_BASE_URL = import.meta.env.MODE === 'development'
  ? '/api/Slave/v1/Permissions'
  : `${import.meta.env.VITE_API_BASE_URL}/Slave/v1/Permissions`;

const PermissionController = {
  getFlatStructure: async (token: string) => {
    try {
      const response = await axios.get(`${API_BASE_URL}/MenusStructure/Flat`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      return response.data;
    } catch (error) {
      console.error('API GET Error:', error);
      throw error;
    }
  }
};

export default PermissionController;

In development, the URL should be http://localhost:10000/Slave/v1/Permissions/MenusStructure/Flat but it stays like this http://127.0.0.1:5173/api/Slave/v1/Permissions/MenusStructure/Flat

I tried several proxy configs, but I can't make it work.


Solution

  • I had to remove the port and just use localhost for it to work.