Create a comment system for articles in Strapi

Create a comment system for articles in Strapi

Create a new content type through Content type Builder as below screen.


To create the comment system add a new field (comments Relation with comment) in existing article content type


Next In Strapi project folder open ** api/article/config/routes.json** file and the new routes.

      "method": "POST",
      "path": "/articles/:id/comment",
      "handler": "article.comment",
      "config": {
        "policies": []

Open *api/article/controllers/article.js * and add the below code.

const { parseMultipartData, sanitizeEntity } = require('strapi-utils');

module.exports = {
  async comment(ctx) {
    let entity;
    if (ctx.is('multipart')) {
      const { data, files } = parseMultipartData(ctx);
      entity = await strapi.services.comment.create(data, { files });
    } else {
      ctx.request.body.author = ctx.state.user.id;
      cts.request.body.article = ctx.params.id;
      entity = await strapi.services.comment.create(ctx.request.body);
    return sanitizeEntity(entity, { model: strapi.models.comment });

Go to Roles & permissions > Authenticated click on edit & select comment checkbox and save the changes so all authenticated user has permission on newly created routes


Now open the postman software to test the comment post first login via the authenticated user to create the token & post the token in authorization header & add prams field value equal to existing article ID.

API URL:- http://localhost:1337/articles/1/comment

'comment':'this is a comment'

On clicking on the submit button as a result you will get the post comment details.


I hope this will help you!

Related Articles