【问题标题】:SyntaxError: Unexpected token t in JSON.parseSyntaxError:JSON.parse 中的意外标记 t
【发布时间】:2020-04-10 05:00:46
【问题描述】:

我想在快递上使用bodyParser。我的posts.js 文件有

const express = require('express');
const router = express.Router();

const Post = require('../models/Post');

router.post('/', (req, res) => {
    console.log(req.body);
});

module.exports = router;

app.js文件上,代码是这样的

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

const postsRoutes = require('./routes/posts');
// const usersRoutes = require('./routes/users');

app.use('/posts', postsRoutes);
// app.use('/users', usersRoutes);

依赖版本是

"body-parser": "^1.19.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"mongoose": "^5.9.7",
"nodemon": "^2.0.3"

服务器连接成功,但是当我在 json 模式下通过邮递员传递数据时,终端显示如下错误 SyntaxError: Unexpected token t in JSON at position 3 at JSON.parse (<anonymous>)... 我在app.js上使用了以下代码

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

因为现在express 已经内置了body-person 功能,但这里的输出相同。

我可以做些什么来解决这个问题?我需要帮助。提前致谢!

【问题讨论】:

  • 由于您使用的是express 4.17.1,因此正文解析器是inbult。代码的第二部分 app.use(express.urlencoded({ extended: true })); app.use(express.json()); 应该足够了,您可以完全删除 body-parser 模块+代码。你如何通过邮递员发布数据,你可以用截图更新问题吗?
  • prntscr.com/rwji9u这是邮递员截图链接
  • 已经根据截图发布了答案,看看是否有效。
  • 是的,现在解决了这个问题。我忘记在邮递员的标题和描述属性中添加“”。现在效果很好。非常感谢

标签: javascript node.js json mongodb express


【解决方案1】:

在 JSON 中的键必须是字符串,在邮递员负载中尝试以下操作:

{
    "title": "Title here",
    "Description": "Description here..."
}

而不是这个:

{
    title: "Title here",
    Description: "Description here..."
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多