【问题标题】:SyntaxError: Unexpected token } in JSON at position 102SyntaxError: Unexpected token } in JSON at position 102
【发布时间】:2020-10-23 15:43:23
【问题描述】:

我创建了一个连接到 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.js mongodb express mongoose


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-11-03
      • 2019-11-17
      • 2019-09-20
      • 1970-01-01
      • 2022-01-22
      • 2021-09-30
      • 2017-12-15
      • 2017-01-17
      • 1970-01-01
      相关资源
      最近更新 更多