我有一个Vue.js项目,我已经配置了一个webpack开发服务器来代理对后端服务器的UI的所有请求。这是vue.config.js的相关部分:
devServer: {
contentBase: PATHS.build,
port: 9000,
https: false,
hot: true,
progress: true,
inline: true,
watchContentBase: true,
proxy: {
'^/': {
target: 'http://127.0.0.1:8089',
secure: false
},
}
},
我注意到如果来自http://127.0.0.1:8089的HTTP响应代码不是2xx,则代理失败并出现以下错误:
代理错误:无法从localhost:9000代理请求/ api / test到http://127.0.0.1:8089。有关更多信息,请参阅https://nodejs.org/api/errors.html#errors_common_system_errors(HPE_INVALID_CHUNK_SIZE)。
这也导致来自localhost:9000的请求的HTTP响应代码为500,因为任何错误都会丢失有关服务器端出错的所有信息。这是有问题的,因为我希望能够从错误响应中提取信息以显示给用户。
我知道这是可能的,因为我有一个较旧的Angular项目,我认为它使用的是Webpack 3(我现在正在使用Webpack 4)。我尝试从这个项目复制所有的dev-server配置,但它似乎在这里不起作用!
编辑:我错了。每个错误响应都不会发生代理错误,但仅针对其中一个请求是多部分文件上载。仍然无法在一个较小的例子中重现这一点,以便穿上github,尽管如此努力查明原因。
我终于找到了问题,我道歉,这是一个特定的问题,而不是我在编写问题时的想法。
问题与使用Spring RestTemplate代理到另一台服务器的请求有关:
EG
@PostMapping("/upload")
public ResponseEntity upload(@RequestParam("file") MultipartFile file)
throws Exception {
String baseUrl = serviceProperties.getAddress();
HttpEntity<MultiValueMap<String, Object>> request = createMultipartRequest(file.getBytes());
return restTemplate.postForEntity(baseUrl + "/api/upload", filterRequest, String.class);
}
从其余模板代理返回的ResponseEntity包含标题“Connection:close”,当响应为200以外会导致连接关闭并导致此请求无法返回任何随后导致dev-server代理失败的情况UI。
通过不将响应标头从其余模板代理传递到响应来解决此问题:
@PostMapping("/upload")
public ResponseEntity upload(@RequestParam("file") MultipartFile file)
throws Exception {
String baseUrl = serviceProperties.getAddress();
HttpEntity<MultiValueMap<String, Object>> request = createMultipartRequest(file.getBytes());
ResponseEntity response = restTemplate.postForEntity(baseUrl + "/api/upload", filterRequest, String.class);
return new ResponseEntity<>(response.getBody(), response.getStatusCode());
}
此错误消息来自node_modules/@vue/cli-service/lib/util/prepareProxy.js
,它定义了node-http-proxy
的onError回调;
所以我做了一些实验,让后端api生成400 404 500响应,但我没有得到这个错误。
在我碰巧关闭后端api后,出现错误:
Proxy error: Could not proxy request /hello from localhost:8080 to http://localhost:8081 (ECONNREFUSED).
我在the doc搜索并找到这些:
如果对目标的请求失败,则会发出错误事件。我们不对客户端和代理之间传递的消息以及代理和目标之间传递的消息进行任何错误处理,因此建议您监听错误并处理它们
所以onError
不处理错误代码,仅在请求失败时调用(500 response
仍被视为完整请求,connection refuse
不是)
回到您的错误消息,[HPE_INVALID_CHUNK_SIZE]表示对后端api的错误请求。在this issue,它提供了一个解决方案:add a keep-alive header
:
devServer: {
publicPath: 'http://localhost:9090/front/static-dev/build/',
port: 9090,
proxy: {
'/**': {
target: 'http://localhost:8080',
secure: false,
changeOrigin: true,
headers: {
Connection: 'keep-alive'
}
},
open: true
}