【问题标题】:Webpack not detecing proxy for local developmentWebpack 未检测到本地开发的代理
【发布时间】:2020-08-03 07:49:06
【问题描述】:

我无法让一个小代理与我的 React 应用程序一起工作。我正在尝试使用一个小型快速服务器来保密一些 API 密钥,以便我的应用程序可以使用第 3 方 API(具体来说是 github API)。我有一个小型快速应用程序正在运行,我可以查询以从.env 文件中获取 API 密钥,并将这些密钥附加到我对第 3 方 API 的请求中。

目前,我可以同时启动前端应用程序和快递应用程序,并且可以使用我的浏览器查询快递应用程序并获得响应。

我正在尝试配置 webpack 以通过这个 express 应用代理我的请求。在我的webpack.config.js 文件中,我有:

//
devServer: {
    port: 8080,
    proxy: {
      '/api/**': {
        target: 'http://localhost:3000',
        secure: false,
        changeOrigin: true
      }
    }
  }
//

前端应用程序在端口8080 上运行,我的Express 应用程序在端口3000 上运行,两者都在localhost 上。

在我的 React 应用程序中,为了尝试测试是否正在检测/使用此代理,我在组件中有以下内容:

//
handleSubmit(event) {
    event.preventDefault();
    fetch('/api/secret')
      .then(res => {
        console.log('RES: ', res)
        res.json()
      })
      .then(data => {
        console.log("Data: ", data)
        return JSON.stringify(data)
      })
    this.props.onSubmit(this.state.username)
  }
//

目前后端代码非常简单,但这里是:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();

// Initialize app
const app = express();
const port = 3000;

// Configure
app.use(bodyParser.json())
app.use(cors())



app.get('/secret', (req, res) => {
  res.status(200)
  res.send({ aSecret: process.env.<API_KEY> })
})

app.listen(port, () => console.log(`App is running on port ${port}`))

在我的package.json 我有以下(相关脚本和依赖项):

...
...
"start": "concurrently --kill-others \"webpack-dev-server\" \"npm run server\"",
    "server": "nodemon server/index.js"
  },
  "babel": {
    "presets": [
      "@babel/preset-env",
      "@babel/preset-react"
    ]
  },
  "dependencies": {
    "prop-types": "^15.7.2",
    "react": "^16.13.0",
    "react-dom": "^16.13.0",
    "react-icons": "^3.9.0"
  },
  "devDependencies": {
    "@babel/core": "^7.8.7",
    "@babel/preset-env": "^7.8.7",
    "@babel/preset-react": "^7.8.3",
    "babel-loader": "^8.0.6",
    "body-parser": "^1.19.0",
    "concurrently": "^5.1.0",
    "cors": "^2.8.5",
    "css-loader": "^3.4.2",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "html-webpack-plugin": "^3.2.0",
    "nodemon": "^2.0.2",
    "style-loader": "^1.1.3",
    "svg-inline-loader": "^0.8.2",
    "webpack": "^4.42.0",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.10.3"
  },
  "proxy": "http://localhost:3000"
}

如您所见,在组件中,我(尝试)向api/secret 发出请求,并希望在响应中取回我存储在.env 中的API 密钥。

当我在浏览器中使用 fetch('http://localhost:3000/secret') 查询此路由时,我能够成功访问 API 密钥,因此我知道当我运行 npm run start 脚本时,React 应用程序和 Express 应用程序同时启动.

当我单击 React 组件中向/api/secret 发送请求的按钮时,我在浏览器控制台中得到以下输出(与我目前在 react 组件中的控制台日志保持一致):

目前我不确定我在 devServer webpack 配置中的 proxy 配置做错了什么。

我可以看到主机名被自动添加到 React 组件中 fetch 中的 /api/secret 前面。

既定目标:Webpack 成功检测到我用来向 3rd 方 (GitHub) API 发送请求的代理服务器。

如果这个问题是重复的,我深表歉意,我已经花了几个小时研究和摆弄这个配置,但未能找到如何配置它。这也是我第一次尝试启动一个小型代理服务器。提前感谢您的帮助!

【问题讨论】:

    标签: node.js reactjs express webpack proxy


    【解决方案1】:

    需要返回 res.json()

    handleSubmit(event) {
        event.preventDefault();
        fetch('/api/secret')
          .then(res => {
            console.log('RES: ', res)
            return res.json()
          })
          .then(data => {
            console.log("Data: ", data)
            return JSON.stringify(data)
          })
        this.props.onSubmit(this.state.username)
      }
    

    【讨论】:

    • 我最初觉得这不正确,但它似乎有效。像往常一样,我犯了一个愚蠢的错误。感谢您的帮助。