node.js - 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",
}
解决方案
JSON 数组不支持最后一项后的逗号。这就是错误的原因。删除所有 JSON 数组中的最后一个逗号。
date: {
type: Date,
default: Date.now,
}, <---
{
"username":"peoplefrom",
"email":"peopleperson@email.com",
"password":"peoplepassword123", <---
}
推荐阅读
- angular7 - Angular 7中Typescript中的滚动条功能
- c# - 带有剃刀的 asp.net MVC 中的复选框列表和其他选项
- android - AndroidX MultiSelectListPreference 设置占位符
- c# - 如何从德语句子中提取日期时间?
- javascript - 为什么我在提示时收到“无法设置 null 的属性‘innerHTML’”
- html - 您可以使用 iframe 从您的页面浏览其他网站吗?
- c# - 如何从列表项中获取 Id 属性
- cloudera - Cloudera Manager 安装 - 找不到主机(单节点)
- ios - 无法复制和解决 Apple 提交的 EXC_CRASH SIGKILL
- keras - 自动keras模型优化崩溃