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

React项目调用Express API遇JSON解析错误,求原因及修正方案

错误原因分析及解决方案

错误根源

你遇到的SyntaxError: Unexpected token '<'错误,本质是前端请求接口后拿到的不是预期的JSON数据,而是HTML内容(比如404错误页面、跨域拦截提示页面),导致JSON解析失败。常见触发场景:

  • 前后端接口路径不匹配,后端返回404 HTML页面
  • 跨域问题:前端和后端端口不同,浏览器同源策略拦截请求,返回跨域相关的HTML提示
  • 后端未正确处理异常:数据库查询或连接出错时,返回了默认的HTML错误页面而非JSON格式错误信息
  • MySQL配置/表结构问题:后端未正确连接数据库,或Products表不存在、SQL语句错误

修复后的完整代码

后端(Express + MySQL)

先安装依赖:

npm install express mysql2 cors body-parser

创建server.js:

const express = require('express');
const mysql = require('mysql2');
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
const PORT = 3001; // 与React默认3000端口区分

// 中间件配置
app.use(cors()); // 解决跨域
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// MySQL连接配置(根据你的XAMPP信息修改)
const db = mysql.createConnection({
  host: 'localhost',
  user: 'root', // XAMPP默认用户名
  password: '', // XAMPP默认密码为空
  database: 'your_db_name' // 替换为你的数据库名
});

// 连接数据库
db.connect(err => {
  if (err) {
    console.error('MySQL连接失败:', err);
    return;
  }
  console.log('MySQL连接成功');
});

// /getdata接口实现
app.get('/getdata', (req, res) => {
  const query = 'SELECT * FROM Products';
  db.query(query, (err, results) => {
    if (err) {
      console.error('数据查询失败:', err);
      return res.status(500).json({ error: '查询数据失败,请检查数据库配置' });
    }
    res.json(results);
  });
});

app.listen(PORT, () => {
  console.log(`后端服务运行在 http://localhost:${PORT}`);
});

前端(React Home.js)

import { useEffect } from 'react';

function Home() {
  useEffect(() => {
    const fetchProducts = async () => {
      try {
        const res = await fetch('http://localhost:3001/getdata');
        if (!res.ok) {
          throw new Error(`请求失败,状态码: ${res.status}`);
        }
        const data = await res.json();
        console.log('获取到的商品数据:', data);
      } catch (err) {
        console.error('获取API数据出错:', err);
      }
    };

    fetchProducts();
  }, []);

  return (
    <div className="home-container">
      {/* 页面内容 */}
    </div>
  );
}

export default Home;

验证步骤

  1. 启动XAMPP的MySQL服务,确认你的数据库和Products表存在
  2. 运行后端:node server.js,控制台需输出"MySQL连接成功"和服务地址
  3. 直接在浏览器访问http://localhost:3001/getdata,确认返回的是JSON格式数据
  4. 启动React项目:npm start,打开浏览器控制台查看是否成功打印数据

内容的提问来源于stack exchange,提问作者Amit Bin Tariqul

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 04:46:11