我正在用来自vite.js的react开发mern堆栈web应用程序,并且有一个问题要处理代理。
我的客户端运行在http://localhost:3000,服务器端运行在http://localhost:5000。
通常,我使用http代理中间件连接我的服务器和客户端,如下所示
src/setupProxy.jsx
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‘导入
export default defineConfig({
plugins: [react()],
server: {
host: true,
port : 3000,
proxy: {
'/api': {
target: 'http://localhost:5000',
changeOrigin: true
}
}
},
})再次尝试过axios调用。
const result = await axios.post('api/users/login', dataToSubmit)
.then(res => res.data);
return result;然而,与我的预期相反,它仍然发送到3000,我不知道哪里出了问题:/
xhr.js:210 POST http://localhost:3000/api/users/login 404 (Not Found)你能告诉我怎么修吗?感谢您的阅读,我们将非常感谢您的帮助。
发布于 2022-05-16 21:22:33
需要像这样指定secure: false。参考文献
export default defineConfig({
plugins: [react()],
server: {
host: true,
port : 3000,
proxy: {
'/api': {
target: 'http://localhost:5000',
changeOrigin: true,
secure: false
}
}
},
})发布于 2022-09-26 20:43:38
我也有这个问题。
后端运行在http://localhost:8080上,而前端运行在http://localhost:3000上。
为了解决跨源问题,我使用了代理选项,但是每个请求都返回一个404错误。
我的解决方案是在vite设置文件中添加rewrite: (path) => path.replace(/^\/api/, "")函数。
最后,文件的最终结果是:
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()],
});https://stackoverflow.com/questions/71994194
复制相似问题