首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我无法在mern堆栈中设置代理( the Vite),也不知道原因

我无法在mern堆栈中设置代理( the Vite),也不知道原因
EN

Stack Overflow用户
提问于 2022-04-25 03:18:43
回答 2查看 1.7K关注 0票数 2

我正在用来自vite.js的react开发mern堆栈web应用程序,并且有一个问题要处理代理。

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

通常,我使用http代理中间件连接我的服务器和客户端,如下所示

src/setupProxy.jsx

代码语言:javascript
复制
const { createProxyMiddleware } = require('http-proxy-middleware');

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

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

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

从'vite‘导入{ defineConfig,HttpProxy }从’@vitejs/plugin‘导入

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

代码语言:javascript
复制
export default defineConfig({
    plugins: [react()],
    server: {
        host: true,
        port : 3000,
        proxy: {
            '/api': {
                target: 'http://localhost:5000',
                changeOrigin: true
            }
        }
        
    },
  

})

再次尝试过axios调用。

代码语言:javascript
复制
const result = await axios.post('api/users/login', dataToSubmit)
                .then(res => res.data);
            return result;

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

代码语言:javascript
复制
xhr.js:210          POST http://localhost:3000/api/users/login 404 (Not Found)

你能告诉我怎么修吗?感谢您的阅读,我们将非常感谢您的帮助。

EN

回答 2

Stack Overflow用户

发布于 2022-05-16 21:22:33

需要像这样指定secure: false参考文献

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

})
票数 0
EN

Stack Overflow用户

发布于 2022-09-26 20:43:38

我也有这个问题。

后端运行在http://localhost:8080上,而前端运行在http://localhost:3000上。

为了解决跨源问题,我使用了代理选项,但是每个请求都返回一个404错误。

我的解决方案是在vite设置文件中添加rewrite: (path) => path.replace(/^\/api/, "")函数。

最后,文件的最终结果是:

代码语言:javascript
复制
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    proxy: {
      "/api": {
        target: "http://127.0.0.1:8080",
        changeOrigin: true,
        secure: false,
        ws: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
    },
    port: 3000,
  },
  plugins: [react()],
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71994194

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档