大响应数据下Angular请求报错net::ERR_FAILED的解决问询
解决Angular请求大文件时net::ERR_FAILED的问题
1. 修正HttpClient的responseType配置
不要使用'blob' as 'json'这种混合类型声明,大文件请求应明确指定responseType: 'blob',避免类型解析冲突导致请求中断:
import { HttpClient } from '@angular/common/http'; constructor(private http: HttpClient) {} downloadLargeFile() { this.http.get('/api/your-endpoint', { responseType: 'blob' }) .subscribe(blob => { // 处理Blob文件,例如下载 const downloadUrl = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = downloadUrl; link.download = 'large-file.dat'; link.click(); window.URL.revokeObjectURL(downloadUrl); }); }
2. 延长请求超时时间
Angular HttpClient默认超时可能不足以处理大文件传输,通过timeout操作符设置更长的超时阈值:
import { timeout } from 'rxjs/operators'; this.http.get('/api/your-endpoint', { responseType: 'blob' }) .pipe(timeout(60000)) // 设置为60秒,根据实际传输需求调整 .subscribe(/* 处理逻辑 */);
3. 优化Angular代理配置
在proxy.conf.json中添加超时设置,并确保响应头处理正确,避免代理截断大文件响应:
{ "/api/*": { "target": "http://your-spring-boot-server", "secure": false, "changeOrigin": true, "timeout": 60000, // 代理层超时匹配请求超时 "onProxyRes": function(proxyRes) { // 若后端使用分块传输,移除Content-Length头避免浏览器解析冲突 delete proxyRes.headers['content-length']; } } }
4. 检查Spring Boot端的服务器配置
确保Tomcat允许大文件传输,避免服务器端截断请求:
在application.properties中添加:
# 禁用Tomcat的请求内容大小限制 server.tomcat.max-swallow-size=-1 # 设置最大请求大小,根据需求调整 server.tomcat.max-http-post-size=20MB
同时确保后端返回正确的Content-Type(如application/octet-stream),并启用分块传输(若未设置Content-Length)。
5. 排除浏览器扩展干扰
禁用Chrome/Edge的所有扩展(如广告拦截器、隐私插件),部分扩展会主动中断大文件请求。
6. 检查CORS预检请求缓存
确保Spring Boot的CORS配置设置了足够长的预检请求缓存时间,避免频繁触发OPTIONS请求:
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "OPTIONS") .allowedHeaders("*") .maxAge(3600); // 预检请求缓存1小时 } }
内容的提问来源于stack exchange,提问作者sgreen
相关产品推荐
相关产品推荐

