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

React中Axios响应如何判断NotFound?状态码不显示问题排查

问题

在React应用中使用Axios发起API调用,用户从两个下拉框选择值作为参数调用接口,正常场景下能返回目标对象,但当无匹配数据时,前端收到的是index.html内容而非预期的404响应。

后端C#控制器代码

[HttpGet("search/{antifungal}/{interacting}")]
public async Task<ActionResult<DrugInteractionDTO>> getAntifungalInteraction(string antifungal, string interacting)
{
    var interactions = await _context.DrugInteractions
        .Include(di => di.AntifungalAgent)
        .Include(di => di.InteractingDrug)
        .Where(di => di.AntifungalAgent.Name.ToLower() == antifungal.ToLower())
        .Where(di => di.InteractingDrug.GenericName.ToLower() == interacting.ToLower())
        .Select(x => new DrugInteractionDTO
        {
            Severity = x.Severity,
            SeverityAsString = x.Severity.ToString(),
            ProDetailedInformation = x.ProDetailedInformation,
            BasicDetailedInformation = x.BasicDetailedInformation,
            Antifungal = x.AntifungalAgent.Name,
            InteractingDrug = x.InteractingDrug.GenericName,
            ID = x.ID
        }).FirstOrDefaultAsync();
    
    if (interactions == null) return NotFound();

    return interactions;
}

Swagger调用无匹配参数的响应

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.4",
  "title": "Not Found",
  "status": 404,
  "traceId": "00-29b4bb56b99fe26416be4e3c09add6b7-dc13efbf731e6a72-00"
}

前端React代码

const getInteractionDetails = () => {
  agent.drugInteractions.getIndividual(antifungalDrug, interactingDrug)
  .then((response) => {
    console.log(response.status)
    if(response.status === 404){
      setError('No interaction exists')
    } else {
      setInteractionDetails(response)
    }
    
  })
  .catch(error => console.log(error))
}

当前问题:前端Axios响应中response.data返回undefined,无法读取response.status,也无法正确判断是否为NotFound。


解决方案

核心原因

这是前端单页应用(SPA)的路由 fallback 配置问题:当后端返回404时,前端的Web服务器(开发环境的React Dev Server或生产环境的Nginx/Apache)没有正确代理API请求,而是直接返回了应用的index.html文件(SPA默认的兜底行为)。这导致Axios收到的是HTML内容,而非预期的404 JSON响应,自然无法读取正确的状态码和响应数据。

修复步骤

1. 修正前端服务器的路由代理配置

  • 开发环境(Create React App):在package.json中添加proxy字段,确保所有API请求转发到后端服务:
    "proxy": "http://localhost:5000" // 替换为你的后端实际地址
    
  • 生产环境(Nginx示例):修改Nginx配置,让API路径直接转发到后端,非API路径才返回index.html:
    location / {
      try_files $uri $uri/ /index.html;
    }
    
    location /api { // 替换为你的API前缀
      proxy_pass http://your-backend-server-ip:port;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
    }
    

2. 调整Axios的错误处理逻辑

Axios默认会将4xx/5xx状态码的响应抛出到catch块中,而非进入then块。需要修改前端代码,在catch中处理404场景:

const getInteractionDetails = () => {
  agent.drugInteractions.getIndividual(antifungalDrug, interactingDrug)
  .then((response) => {
    setInteractionDetails(response.data)
  })
  .catch(error => {
    // 通过error.response获取后端返回的错误响应
    if (error.response?.status === 404) {
      setError('No interaction exists')
    } else {
      console.log('请求出错:', error)
    }
  })
}

3. 验证后端响应格式

通过Postman直接调用接口,确认无匹配数据时后端返回的是application/json格式的404响应,且响应头配置正确。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 09:45:46