node.js - Cannot process POST request in Sails.js correctly -
i'm trying add comments functionality sails.js blog application. however, don't seem write controller action correctly.
when submit comment form, page starts reload, not finish reloading.
here's controller code:
const gravatar = require('gravatar'); module.exports = { blog: (req, res) => { post.find({}).exec((err, posts) => { if (err) { res.send(500, { error: 'database error' }); } res.view('all-posts', { posts }); }); }, singlepost: (req, res) => { post.findonebyslug(req.params.slug).exec((err, post) => { if (err) { res.send(500, { error: 'database error' }); } res.view('single-post', { post, gravatar: gravatar.url }); }); }, addcomment: (req, res) => { const { name, comment, email, url, slug, } = req.allparams(); post.findonebyslug(slug).exec((err, post) => { if (err) { return res.send(500, { error: 'database error' }); comment.create({ body: comment, name, email, website: url }).exec((error, comment) => { if (error) { return res.send(500, { error: 'database error' }); } console.log(comment); post.comments.addcomment({slug, comment}); post.save(); res.redirect(`/${slug}`); }); } }); return false; }, };
and here's routes.js
file:
module.exports.routes = { 'get /blog': 'blogcontroller.blog', 'get /:slug': 'blogcontroller.singlepost', 'post /:slug/new-comment': 'blogcontroller.addcomment' };
and model post.js
module.exports = { identity: 'post', attributes: { title: { type: 'string', required: true, unique: true }, body: { type: 'string' }, categories: { type: 'string', required: true }, imageurl: { type: 'string' }, comments: { collection: 'comment', via: 'post' }, slug: { type: 'slug', from: 'title', blacklist: ['search', 'blog', 'contacts'] } }, addcomment: (options, cb) => { post.findonebyslug(options.slug).exec((err, post) => { if (err) return cb(err); if (!post) return cb(new error('post not found.')); post.comments.add(options.comment); post.save(cb); }) }, connection: 'mongodb' };
so, when submit comment form on /:slug
page, nothing happens accept page tries reload. , in database nothing gets saved well.
the form parameters sent form, on client side should fine.
how how approach post request correctly?
you need add return
statement before each res.send(500, ...);
call, because currently, in case of error, code tries send response twice, , client doesn't response actual error:
if (err) { return res.send(500, { error: 'database error' }); } ... rest code
i suspect, reason why nothing saved in db invalid parameters in request body.
Comments
Post a Comment