'I can't setup proxy in mern stack(react-vite) and do not know the reason

I'm developing mern stack web application with react from vite.js and have a problem to deal with proxy.

my client side runs at http://localhost:3000 and server side runs at http://localhost:5000.

usually I use http-proxy-midlleware to connect my server and client like below

src/setupProxy.jsx

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app){
  app.use(
      createProxyMiddleware('/api', {
          target: 'http://localhost:5000',
          changeOrigin: true
      })
  )
};

However, It didn't work and still sent to localhost:3000 when I post data to server with axios. I googled it and figured out that with vite.js I need to use vite.config.js

so I set up vite.config.js like below

import { defineConfig, HttpProxy } from 'vite' import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/

export default defineConfig({
    plugins: [react()],
    server: {
        host: true,
        port : 3000,
        proxy: {
            '/api': {
                target: 'http://localhost:5000',
                changeOrigin: true
            }
        }
        
    },
  

})

and tried axios call again.

const result = await axios.post('api/users/login', dataToSubmit)
                .then(res => res.data);
            return result;

However, contrary to my expectation, It still sent to 3000 and I do not have a clue about what is going wrong :/

xhr.js:210          POST http://localhost:3000/api/users/login 404 (Not Found)

could you tell me how to fix it? thanks for reading, your help will be appreciated.



Solution 1:[1]

It's required to specify secure: false like this. Reference

export default defineConfig({
    plugins: [react()],
    server: {
        host: true,
        port : 3000,
        proxy: {
            '/api': {
                target: 'http://localhost:5000',
                changeOrigin: true,
                secure: false
            }
        }
        
    },
  

})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pakut2