我们在 React 应用程序的 package.json
中定义了代理(创建为 create-react-app。我们在开发过程中在前端(webpack)和后端(express)之间使用代理 described here 。这是我们定义后端服务器代理的部分(package.json
:
"scripts": {
...
},
"proxy": "http://localhost:3001"
}
在后端(服务器在端口 3001
上运行),我们调用另一个 API(但我认为这并不重要,只是一个注释)。
我注意到从 webpack (create-react-app) 到 express (backed) 的代理调用非常慢。 (Windows 操作系统)
GET http://localhost:3000/endpoint/ -> ~600ms - 900ms
GET http://localhost:3001/endpoint/ -> ~150ms - 250ms
正如您所看到的,代理调用(端口 3000)和直接调用(端口 (3001))之间的时间差异确实很大。我预计会有延迟,但这看起来很奇怪。
此外,有时来自代理的大型 JSON 响应 (~38KB
) 会被破坏(无效 - 例如,在 30%+
情况下缺少响应的某些部分或交换字符)。我一直在后端遇到同样的问题,我想我已经通过设置 keep-alive
连接的 proxy-agent 解决了这个问题。
您知道为什么或如何改进代理时间和行为吗?
我还尝试在package.json
中设置代理,但没有成功。
create react app documentation说:
You may also specify any configuration value http-proxy-middleware or http-proxy supports.
agent: object to be passed to http(s).request (see Node's https agent and http agent objects)
是否可以在package.json
中定义代理?
我尝试过,但出现以下错误
TypeError: Agent option must be an Agent-like object, undefined, or false. at new ClientRequest (_http_client.js:106:11)
"proxy": {
"/": {
"target": "http://localhost:3001",
"agent": { "keepAlive": true }
}
}
非常感谢任何建议或想法。
最佳答案
添加我的问题的答案,以防有人遇到与我们相同的问题。
我们被迫使用react-app-rewired对于定制代理。遗憾的是,我们无法为 devServer
代理设置自定义代理。
如果您需要更改 devServer 的代理,documentation 中的解释非常好。 .
// config-overrides.js
module.exports = {
devServer: function(configFunction) {
return function(proxy, allowedHost) {
const config = configFunction(proxy, allowedHost);
config.proxy.forEach(p => {
p.agent = agent;
});
return config;
};
}
}
我猜这是一种解决方法,在 create-react-app
的 future 版本中可能不支持但响应时间约为 150 毫秒 - 230 毫秒(并且!没有无效的 JSON),这才是现在最重要的。 。
来自 react-app-rewired
的令人不安的注释我想指出:
By doing this you're breaking the "guarantees" that CRA provides. That is to say you now "own" the configs. No support will be provided. Proceed with caution.
关于javascript - React 在 package.json 中创建应用程序代理在 Windows 上速度很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48954803/