我正在尝试将我的字符串保存到逗号分隔的数组中,但是当我尝试使用JSON.parse
方法时,我在发送post方法并尝试保存记录时收到此错误:
SyntaxError: Unexpected token c
at Object.parse (native)
at router.route.post.get.res.render.blogpost (/Users/user/Desktop/Projects/node/blog/app/routes.js:106:34)
这是我的路线(来自blogpost.save的错误):
router.route('/admin/posts/create')
// START POST method
.post(function(req, res) {
console.log("New instance");
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.featureImage = req.body.featureImage; // set the blog image
blogpost.blogUrl = blogpost.title.toLowerCase().replace(/\s+/g,"-");
blogpost.author = req.body.author; // set the author name
blogpost.tagline = req.body.tagline; // set the tagline
blogpost.content = req.body.content; // set the blog content
blogpost.category = req.body.category; // set the category
blogpost.tags = JSON.parse(req.body.tags.split(",")); // set the tags
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.redirect(303, '/'); //NEEDS TO BE CHANGED
});
}) // END POST method
.get(isLoggedIn, function(req, res, blogpost) {
res.render('pages/blogpost-create', {
blogpost : blogpost
});
});
答案 0 :(得分:4)
JSON.parse
将一个字符串(有效的JSON)解析为一个对象/数组。
你已经有了一个数组,正如你正在做的那样
req.body.tags.split(",")
和split()
创建一个数组。你无法解析数组,但你可以将其字符串化