首页 > 解决方案 > Webpack devServer 不会代理从前端到后端服务器的请求

问题描述

我正在为一个项目构建一个苗条/快速的应用程序。我在端口 3000 上运行我的 express 服务器,在端口 8080 上运行我的苗条应用程序,由于某种原因,我根本无法让 devServer 代理工作。我已经查看了与此相关的其他线程,甚至尝试了他们的修复,仍然没有。我正在从客户端 package.json 启动 devServer,同时由服务器 package.json 调用。在浏览器控制台中查看时,我收到一个 404 错误,从 8080 端口调用我的端点(POST http://localhost:8080/api/auth/login insead of POST http://localhost:3000/api/auth /按预期登录)

webpack.config.js

devServer: {
        proxy: {
            '/api': {
                target: 'http://localhost:3000',
                changeOrigin: true,
                pathRewrite: { '^/api': '' },
            },
        },
    },

客户端包.json

{
  "name": "svelte-app",
  "version": "1.0.0",
  "devDependencies": {
    "cross-env": "^7.0.3",
    "css-loader": "^5.0.1",
    "mini-css-extract-plugin": "^1.3.4",
    "svelte": "^3.31.2",
    "svelte-loader": "^3.0.0",
    "webpack": "^5.16.0",
    "webpack-cli": "^4.4.0",
    "webpack-dev-server": "^3.11.2"
  },
  "scripts": {
    "build": "cross-env NODE_ENV=production webpack",
    "dev": "webpack serve --content-base public"
  },

服务器包.json

"scripts": {
    "start": "node server.js",
    "build": "cd client && npm install && npm run build",
    "server": "nodemon server.js --ignore 'client'",
    "client": "cd client && npm run dev",
    "dev": "concurrently \"npm run server\" \"npm run client\""
  },

标签: node.jswebpackwebpack-dev-serversvelte

解决方案


推荐阅读