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

Express项目JSON解析报错:Unexpected token '<' 求助

问题解决:JSON解析时遇到Unexpected token '<'错误

核心原因

  1. 客户端用XMLHttpRequest发送的是GET请求,但后端只定义了POST /testing/thisshit路由,服务器找不到对应路由,返回404错误的HTML页面,导致JSON解析时碰到<符号报错。
  2. 后端重复调用app.listen,启动了两个端口,导致第一个端口的服务失效,可能造成请求端口不匹配。
  3. 手动拼接JSON字符串返回,容易出错且未正确设置响应头。

1. 服务器端(index.js)修改方案

const express = require('express');
const app = express();

// 静态文件服务,确保HTML能被访问
app.use(express.static('public'));
// 内置解析中间件,替代单独的body-parser
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// 添加GET路由,匹配客户端的GET请求
app.get('/testing/thisshit', (req, res) => {
  // 用res.json自动处理JSON转换和响应头
  res.json({ message: "potatohead" });
});

// 保留POST路由,对应jQuery的post请求
app.post('/testing/thisshit', async (req, res) => {
  console.log(req.body);
  res.json({ message: "potatohead" });
});

// 只保留一个监听端口,避免冲突
app.listen(8080, () => {
  console.log('server started on port 8080');
});

2. 客户端(something.js)修改方案

如果你想继续用GET请求,上面的服务器修改已经支持;如果要改成POST请求,调整如下:

console.log('testing')
var abcd = {juice: "juice"}
$.post( '/testing/thisshit', abcd);

var res = new XMLHttpRequest();
var url = '/testing/thisshit';
res.open('POST', url, true);
// 设置请求头,告知服务器请求体是JSON
res.setRequestHeader('Content-Type', 'application/json');
res.addEventListener('load', onLoad);
res.addEventListener('error', onError);
// 发送JSON格式的请求体
res.send(JSON.stringify(abcd));

function onLoad() {
  var response = this.responseText;
  console.log(response);
  try {
    var parsedResponse = JSON.parse(response);
    console.log("the result: ", parsedResponse);
  } catch (err) {
    // 捕获解析错误,方便调试
    console.error('JSON解析失败:', err);
    console.error('响应内容:', response);
  }
}
function onError() {
  console.log('请求错误');
}

调试小技巧

  • 打开浏览器开发者工具的网络面板,查看请求的状态码和响应内容,确认是否返回预期的JSON
  • 确保HTML文件放在public目录下,express静态服务能正确访问
  • 启动服务器后,访问http://localhost:8080确认页面正常加载

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 03:15:48