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

POST请求localhost:4000/rooms/book/1时JSON解析错误排查求助

会议室预订API JSON解析错误排查

问题描述

开发基于Express框架的会议室预订API时,向POST接口localhost:4000/rooms/book/1发送测试请求,终端抛出JSON解析语法错误,需定位问题。

API代码

const express = require("express");
const { body, validationResult } = require("express-validator");

const app = express();
const PORT = 4000;

app.use(express.json());

const rooms = [];
const booking = [];

// 创建会议室
app.post(
  "/rooms/create",
  [
    body("seatsAvailable").notEmpty().isInt(),
    body("amenities").notEmpty().isArray(),
    body("pricePerHour").notEmpty().isFloat(),
  ],
  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).send({ errors: errors.array() });
    }

    const room = {};
    room.id = rooms.length + 1;
    Object.assign(room, req.body);
    rooms.push(room);
    res.status(201).send(room);
  }
);

// 预订会议室
app.post(
  "/rooms/book/:roomId",
  [
    body("customerName").notEmpty().isAlphanumeric(),
    body("dateOfBooking").notEmpty().isDate(),
    body("startTime").notEmpty().isString(),
    body("endTime").notEmpty().isString(),
    body("seatsRequired").notEmpty().isInt(),
  ],
  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).send({ errors: errors.array() });
    }
    if (rooms.length === 0) {
      return res.status(404).send({ message: "No rooms available" });
    }
    const roomId = req.params.roomId;
    const room = rooms.find((room) => room.id == parseInt(roomId));
    if (!room) {
      return res
        .status(404)
        .send({ message: `Room is not found with number ${roomId}` });
    }

    console.log(room);
  }
);

// 获取所有会议室
app.get("/rooms", (req, res) => {
  res.send(rooms);
});

app.listen(PORT, () => {
  console.log("server connected successfully!");
});

终端错误日志

node index.js 
server connected successfully!
SyntaxError: Expected ',' or '}' after property value in JSON at position 54
    at JSON.parse (<anonymous>)
    at parse (/home/shri/Desktop/Roadmap-Day38-Hall-Booking-API/node_modules/body-parser/lib/types/json.js:92:19)
    at /home/shri/Desktop/Roadmap-Day38-Hall-Booking-API/node_modules/body-parser/lib/read.js:128:18
    at AsyncResource.runInAsyncScope (node:async_hooks:206:9)
    at invokeCallback (/home/shri/Desktop/Roadmap-Day38-Hall-Booking-API/node_modules/raw-body/index.js:238:16)
    at done (/home/shri/Desktop/Roadmap-Day38-Hall-Booking-API/node_modules/raw-body/index.js:227:7)
    at IncomingMessage.onEnd (/home/shri/Desktop/Roadmap-Day38-Hall-Booking-API/node_modules/raw-body/index.js:287:7)
    at IncomingMessage.emit (node:events:518:28)
    at endReadableNT (node:internal/streams/readable:1696:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

请求信息

  • 请求方法:POST
  • 请求地址:localhost:4000/rooms/book/1
  • 请求体:
{
    "customerName": "Jeeva",
    "dateOfBooking": 12-04-2024,
    "startTime": "10.00 AM",
    "endTime": "1.00 PM",
    "seatsRequired": 2
}

问题定位与解决

错误原因

JSON解析错误的核心原因是请求体中dateOfBooking字段的值12-04-2024未用双引号包裹。JSON语法要求所有字符串类型的值必须用双引号括起来,直接写12-04-2024会被解析器识别为减法表达式(12减4减2024),违反JSON语法规则,导致解析失败。

修复方案

将请求体中的dateOfBooking值加上双引号,修正后的请求体如下:

{
    "customerName": "Jeeva",
    "dateOfBooking": "12-04-2024",
    "startTime": "10.00 AM",
    "endTime": "1.00 PM",
    "seatsRequired": 2
}

额外说明

虽然代码中使用express-validator的isDate()规则验证dateOfBooking字段,但该验证的前提是请求体能被正常解析为JSON。因此必须先修复请求体的语法错误,才能触发后续的业务逻辑验证。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 23:32:22