如何为Create React App配置代理对接ASP.NET Core 6.0 Web API
问题描述
React项目尝试从ASP.NET Core 6 Web API拉取数据,通过Swagger调用https://localhost:7119/Sitemap能得到正确结果,但React中用代理访问该URL时,返回的却是React根目录的index.html内容(<!Doctype...>)。
此前直接在fetch里使用完整路径时还遇到过CORS错误,本以为createProxyMiddleware能解决该问题,但目前请求似乎仍从http://localhost:3000/sitemap获取数据,并未走代理。
现有代码
Fetch调用代码
await fetch("sitemap", { method: 'GET' , headers: { 'Content-Type': 'application/json' } , credentials: 'include' // ADDED , redirect: 'follow' , mode: 'cors' }) .then(resp => { let tmp = resp.json(); return tmp; }) .then(res => { dispatch({ type: ActionTypes.SITEMAP_LOADED, payload: res }) })
setupProxy.js代码
/* module.exports = (app) => { app.use(createProxyMiddleware('/*', { target: 'https://localhost:7119/', changeOrigin: true, logLevel: "debug" })); // mock(app); }; */ //**** This has been modified to: const contexts= { "/Sitemap" } module.exports = (app) => { app.use(createProxyMiddleware(contexts, { target: 'https://localhost:7119/', secure:true, changeOrigin: true, logLevel: "debug" })); // mock(app); };
更新后的错误
修改配置后,命令提示符出现以下错误,每个请求文件都会生成两条消息:
[HPM] Error occurred while proxying request localhost:3000/manifest.json to https://localhost:7119/ [DEPTH_ZERO_SELF_SIGNED_CERT]
以及
[HPM] Error occurred while proxying request localhost:3000/manifest.json to https://localhost:7119/ [ECONNREFUSED]
解决方案
1. 修复代理路径匹配问题
contexts定义存在语法错误,应为数组而非对象;同时要注意大小写匹配——ASP.NET路由区分大小写,你Fetch请求的是小写sitemap,但代理配置的是大写/Sitemap,这会导致代理不生效,请求落到React路由上返回index.html。
修改setupProxy.js:
const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = (app) => { // 匹配小写的/sitemap,避免代理所有静态资源请求 app.use(createProxyMiddleware('/sitemap', { target: 'https://localhost:7119/', changeOrigin: true, logLevel: "debug", // 解决自签名证书问题 secure: false })); };
2. 解决自签名证书与连接拒绝错误
DEPTH_ZERO_SELF_SIGNED_CERT:API使用的是自签名HTTPS证书,代理默认会验证证书有效性,设置secure: false可跳过证书校验(仅开发环境使用,生产环境请使用正规证书)。ECONNREFUSED:确认ASP.NET Core API是否正常启动在https://localhost:7119/,端口是否匹配,防火墙是否拦截,或者API是否绑定了正确的IP(比如是否仅绑定127.0.0.1,导致代理无法访问)。
3. 优化Fetch请求
去掉不必要的mode: 'cors'(使用代理时无需跨域配置,代理会转发请求),同时增加错误处理,避免请求失败时出现未捕获异常:
await fetch("/sitemap", { method: 'GET', headers: { 'Content-Type': 'application/json' }, credentials: 'include' }) .then(resp => { if (!resp.ok) { throw new Error(`请求失败: ${resp.status}`); } return resp.json(); }) .then(res => { dispatch({ type: ActionTypes.SITEMAP_LOADED, payload: res }) }) .catch(err => { console.error("加载站点地图失败:", err); });
4. 验证代理是否生效
启动React项目后,查看控制台的HPM日志,若看到类似[HPM] Proxy created: /sitemap -> https://localhost:7119/的信息,说明代理配置成功。此时请求/sitemap时,日志会显示代理转发记录,证明请求已发送到API服务器。
内容的提问来源于stack exchange,提问作者Geoff
相关产品推荐
相关产品推荐

