我无法在 meern stack(react-vite) 中设置代理,并且不知道原因

geo*_*geo 9 proxy node.js reactjs vite

我正在使用 vite.js 的 React 开发 Mern Stack Web 应用程序,并且在处理代理时遇到问题。

我的客户端运行在http://localhost:3000,服务器端运行在http://localhost:5000

通常我使用 http-proxy-midlleware 来连接我的服务器和客户端,如下所示

src/setupProxy.jsx

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

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

但是,当我使用 axios 将数据发布到服务器时,它不起作用,仍然发送到 localhost:3000。我用谷歌搜索了一下,发现使用 vite.js 我需要使用 vite.config.js

所以我设置了 vite.config.js 如下

从'vite'导入{defineConfig,HttpProxy}从'@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
            }
        }
        
    },
  

})
Run Code Online (Sandbox Code Playgroud)

并再次尝试 axios 调用。

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

然而,与我的预期相反,它仍然发送到 3000,我不知道出了什么问题:/

xhr.js:210          POST http://localhost:3000/api/users/login 404 (Not Found)
Run Code Online (Sandbox Code Playgroud)

你能告诉我如何解决它吗?感谢您的阅读,我们将不胜感激您的帮助。

pak*_*ut2 8

需要secure: false这样指定。参考

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

})
Run Code Online (Sandbox Code Playgroud)