Search code examples
node.jspostsails.jssails-mongo

Cannot process POST request in Sails.js correctly


I'm trying to add comments functionality into my Sails.js blog application. However, I don't seem to write my controller action correctly.

When I submit the comment form, the page starts to reload, but does not finish reloading.

Here's my 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 my routes.js file:

module.exports.routes = {
  'get /blog': 'BlogController.blog',

  'get /:slug': 'BlogController.singlePost',

  'post /:slug/new-comment': 'BlogController.addComment'
};

And this is my 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 I submit the comment form on the /:slug page, nothing actually happens accept the page tries to reload. And in the database nothing gets saved as well.

The form parameters get sent from the form, so on the client side everything should be fine.


How how I approach this post request correctly?


Solution

  • You need to add return statement before each res.send(500, ...); call, because currently, in the case of the error, your code tries to send the response twice, and client doesn't get the response with the actual error:

    if (err) {
      return res.send(500, { error: 'Database Error' });
    }
    ... rest code
    

    I suspect, that the reason why nothing is saved in db is invalid parameters in request body.