You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VS2022 React模板中Fetch POST返回404及CORS问题排查

React POST请求404及跨域/连接拒绝问题排查

背景

使用Visual Studio 2022默认React模板创建应用,通过按钮点击事件调用Fetch POST向Web服务器提交数据,返回404提示端点未找到;GET请求可正常工作,但尝试不同地址时还出现连接拒绝和CORS跨域错误。

前端POST请求代码

async postChoresData() {
    const response = await fetch(
        'https://localhost:44400/Chores/PostData',
        {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ data: 'React POST Request Example' })
        }
    );
    const data = await response.json();
}

后端POST接口代码

[ApiController]
[Route("[controller]")]
public class ChoresController : ControllerBase
{
    ...
    [HttpPost]
    public bool PostData(string data)
    {
        return true;
    }
}

正常工作的GET请求示例

前端代码

const response = await fetch('chores');
const data = await response.json();

后端代码

[ApiController]
[Route("[controller]")]
public class ChoresController : ControllerBase
{
    ...
    [HttpGet]
    public IEnumerable<Chore> Get()
    {
        return _choreRepository.LoadChores();
    }
}

运行时控制台信息

https://localhost:7002
[HPM] Proxy created: [ '/weatherforecast', '/chores' ]  ->  https://localhost:7002
i 「wds」: Project is running at https://10.100.244.8/

其他尝试的异常情况

  • 请求https://10.100.244.8/Chores/PostData时出现连接拒绝错误
  • 请求https://localhost:7002/Chores/PostData时出现CORS跨域错误

问题原因分析

  1. POST请求404的核心原因

    • 路由不匹配:后端PostData方法仅标记[HttpPost],结合控制器的[Route("[controller]")],接口实际地址是https://localhost:44400/Chores,而非你请求的Chores/PostData。若要保留PostData作为路由后缀,需给[HttpPost]添加模板,比如[HttpPost("PostData")]。
    • 参数绑定失败:你用JSON格式传递data参数,但后端方法直接用string data接收,ASP.NET Core默认不会从JSON请求体绑定简单类型参数,需给参数添加[FromBody]特性,否则参数会为null,也可能导致路由匹配异常。
  2. 连接拒绝错误的原因

    • https://10.100.244.8是React开发服务器的局域网访问地址,你的后端服务并未部署在该地址上,直接请求此地址的接口自然会连接失败,后端服务实际运行在localhost:44400或localhost:7002。
  3. CORS跨域错误的原因

    • React开发服务器与后端服务运行在不同地址,直接请求https://localhost:7002属于跨域请求,后端服务未配置CORS允许React服务器的来源,因此浏览器拦截了该请求。

内容的提问来源于stack exchange,提问作者Pigfaricus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 08:18:21