You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React前端开发服务器连接Node后端代理配置失败求助

开发环境代理配置失败问题

Node后端运行在8000端口,前端开发服务器在9002端口。尝试多种代理配置方式均失败,怀疑和"type": "module"配置有关,使用http-proxy-middleware也未成功。

后端的/properties接口在Postman及前端部署到8000端口时能正常响应,但前端在9002端口请求该接口时出现404错误。需要解决开发环境代理问题,避免每次改UI都要构建。


相关代码片段

package.json

{
  "name": "properties-three", 
  "version": "1.0.0", 
  "description": "",
  "main": "index.js", 
  "type": "module", 
  "proxy": "http://localhost:8000", 
  "scripts": 
  { 
      "test": "echo \"Error: no test specified\" && exit 1", 
      "dev": "webpack-dev-server --open --config webpack.config.cjs", 
      "start": "nodemon --use_strict server.mjs", 
      "build": "webpack --mode production" 
  }, 
  "author": "", 
  "license": "ISC", 
  "devDependencies": { 
      "@babel/core": "^7.19.6", 
      "@babel/preset-env": "^7.19.4", 
      "@babel/preset-react": "^7.18.6",
       "babel-loader": "^8.2.5", 
      "copy-webpack-plugin": "^11.0.0", 
      "html-webpack-plugin": "^5.5.0", 
      "webpack": "^5.74.0",
       "webpack-cli": "^4.10.0" 
  }, 
  "dependencies": { 
      "axios": "^1.1.3", 
      "cors": "^2.8.5", 
      "express": "^4.18.2", 
      "http-proxy-middleware": "^2.0.6",
      "react": "^18.2.0", 
      "react-dom": "^18.2.0",
      "react-router-dom": "^6.4.2", 
      "webpack-dev-server": "^4.11.1" 
  }
}

setupProxy.js

import {createProxyMiddleware} from "http-proxy-middleware";

module.exports = function(app) {
   app.use(
       '/api/properties',
       createProxyMiddleware({
           target: 'http://localhost:8000',
           changeOrigin: true,
           secure: false,
           ws: true
       })
   );
};

webpack.config.cjs

const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require('path');

const htmlPlugin = new HtmlWebPackPlugin({
    template: "./src/index.html",
    filename: "./index.html"
});
module.exports = {
    entry: "./src/index.js",
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: "bundle.js",
        publicPath: "/"
    },
    devServer: {
        port: 9002,
        static: path.join(__dirname, 'dist'),
        hot: true,
        historyApiFallback: true
    },
    resolve: {
        extensions: ['.ts', ".js", ".jsx"],
    },
    mode: "development",
    plugins: [htmlPlugin],
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            }
        ]
    }
};

server.mjs

import express from 'express';
import cors from 'cors';
import path from "path";
import properties from './routes/properties.routes.js'
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);

const __dirname = path.dirname(__filename);

const app = express();
const PORT = 8000;

app.use(express.static(`${process.cwd()}/build`));
app.use(express.static(`${process.cwd()}/public`));

app.use(cors());
app.use(express.json());

app.use("/properties", properties);

app.use(express.static(path.join(__dirname, '/dist')));

app.get('/*', function (req, res) {
    res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

app.listen(PORT, () => console.log(`server is running on http://locahost:${PORT}`));

App.js

import React, {useState, useEffect} from "react";
import axios from "axios";

function App() {
    const [properties, setProperties] = useState([]);
    useEffect(() =>{
        axios.get('/properties').then((response) =>{
            setProperties(response.data)
        })
    }, []);
    return (
        <div className="App">Test</div>
    );
}

export default App;

问题修复方案

1. 解决模块格式冲突

项目启用了"type": "module",但setupProxy.js混用了ES模块的import和CommonJS的module.exports,导致无法被webpack-dev-server正确加载。将其改为纯ES模块格式,文件名改为setupProxy.mjs:

import { createProxyMiddleware } from "http-proxy-middleware";

export default function(app) {
  app.use(
    '/properties', // 和后端接口路径保持一致,无需额外前缀
    createProxyMiddleware({
      target: 'http://localhost:8000',
      changeOrigin: true,
      secure: false
    })
  );
}

2. 直接在webpack配置中添加代理(更简单)

自定义webpack-dev-server不会读取package.json中的proxy字段,也不一定自动加载setupProxy文件,直接在webpack.config.cjs的devServer里配置代理:

devServer: {
  port: 9002,
  static: path.join(__dirname, 'dist'),
  hot: true,
  historyApiFallback: true,
  // 添加代理配置
  proxy: {
    '/properties': {
      target: 'http://localhost:8000',
      changeOrigin: true,
      secure: false
    }
  }
}

3. 路径匹配问题

如果要给请求加/api前缀,必须配置路径重写,否则会转发到后端不存在的/api/properties路由:

proxy: {
  '/api': {
    target: 'http://localhost:8000',
    changeOrigin: true,
    secure: false,
    pathRewrite: { '^/api': '' } // 去掉/api前缀,转发到后端的/properties
  }
}

此时前端请求要改为axios.get('/api/properties')。

4. 清理无效配置

删掉package.json中的"proxy": "http://localhost:8000",这个配置只对create-react-app默认的开发服务器生效,自定义webpack配置用不上。

5. 重启服务

修改配置后必须重启webpack-dev-server,否则新配置不会生效。

内容的提问来源于stack exchange,提问作者frederickpenn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 13:30:54