首页 > 解决方案 > SyntaxError: Unexpected token } in JSON at position 102

问题描述

我创建了一个连接到 mongo atlas 的简单节点/express api,我尝试发送 post 请求以在 vscode 中使用 rest 客户端扩展向数据库添加新数据,但继续遇到上述错误,不确定我的代码在哪里搞砸了

带有中间件的主服务器文件

const express = require("express");
const app = express();
const coolapi = require("./api/coolapi");
const dotenv = require("dotenv");
const mongoose = require("mongoose");

dotenv.config();

mongoose.connect(process.env.DB_ACCESS, { useUnifiedTopology: true }, () => {
  console.log("DB connected");
});

app.use(express.json());

app.use("/api/coolapi", coolapi);

app.listen(3000, () => {
  console.log("server is running");
});

带有快速路由器的文件

const express = require("express");
const router = express.Router();
const coolioObj = require("../models/CoolModel");

router.post("/signup", (request, response) => {
  const coolPerson = new coolioObj({
    username: request.body.username,
    email: request.body.email,
    password: request.body.password,
  });
  coolPerson
    .save()
    .then((data) => {
      response.json(data);
    })
    .catch((error) => {
      response.json(error);
    });
});

module.exports = router;

带有猫鼬模式的文件

const mongoose = require("mongoose");

const coolioSchema = mongoose.Schema({
  username: {
    type: String,
    required: true,
  },

  email: {
    type: String,
    required: true,
  },

  password: {
    type: String,
    required: true,
  },

  date: {
    type: Date,
    default: Date.now,
  },
});

module.exports = mongoose.model("coolioDB", coolioSchema);

发送请求

POST http://localhost:3000/api/coolapi/signup http/1.1
Content-Type: application/json

{
    "username":"samthingsoweto",
    "email":"sams@amapiano.co",
    "password":"KabzaDaSmall",
}

标签: node.jsmongodbexpressmongoose

解决方案


JSON 数组不支持最后一项后的逗号。这就是错误的原因。删除所有 JSON 数组中的最后一个逗号。

 date: {
    type: Date,
    default: Date.now,
  }, <---
{
    "username":"peoplefrom",
    "email":"peopleperson@email.com",
    "password":"peoplepassword123", <---
}

推荐阅读