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

使用Axios连接前后端出现TypeError错误,Postman测试正常

解决Axios报错:TypeError: error.JSON is not a function

错误根源

你的代码里console.log(error.JSON());存在两个核心问题:

  1. 拼写错误:正确的方法名是小写的json(),而非大写的JSON()
  2. Axios错误对象处理逻辑错误:Axios的错误对象有特定结构,直接调用json()不符合它的错误处理规则

修正步骤

1. 修复错误处理代码

修改Login.js中handleLogin函数的catch块,替换错误的调用方式并优化错误信息捕获:

.catch((error) => {
  let errorMsg = 'An error occurred. Check your network and try again';
  // 分场景处理Axios错误
  if (error.response) {
    // 服务器返回错误响应(如4xx/5xx状态码)
    errorMsg = error.response.data.message || errorMsg;
    console.log('服务器错误详情:', error.response.data);
  } else if (error.request) {
    // 请求已发送但无响应
    console.log('请求无响应:', error.request);
  } else {
    // 请求配置阶段出错
    console.log('请求配置错误:', error.message);
  }
  setSubmitting(false);
  handleMessage(errorMsg);
});

2. 复用已配置的Axios实例

你已经在api/client.js中创建了带baseURL的Axios实例,建议直接引入使用,避免重复编写接口地址:

// 替换Login.js中的axios引入语句
import apiClient from './../api/client';

// 修改handleLogin中的请求逻辑
const handleLogin = (credentials, setSubmitting) => {
  handleMessage(null);

  apiClient
    .post('/signin', credentials)
    .then((response) => {
      // 原成功逻辑保持不变
      const result = response.data;
      const { message, status, data } = result;

      if (status !== 'SUCCESS') {
        handleMessage(message, status);
      } else {
        navigation.navigate('Welcome', { ...data[0] });
      }
      setSubmitting(false);
    })
    .catch((error) => {
      // 使用上面修正后的错误处理逻辑
    });
};

额外优化建议

  • 后端signin接口中,User.find({ email })返回的是数组,当前代码if (data)会始终为true(空数组属于truthy值),建议改为if (data.length > 0),避免后续取data[0]时出现数组越界问题
  • 统一后端接口的HTTP状态码:成功返回200,错误返回对应4xx/5xx状态码,符合REST规范的同时,能让Axios更精准地触发错误分支

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:45:38