Building an e-Commerce website with Node – Part 28 – Create routes for adding product categories in Node.js

Under the routes folder create a file and name it admin.js. In the admin.js file type the following code:

var router = require('express').Router();
var Category = require('../models/category');

router.get('/add-category', function(req, res, next) {
  res.render('admin/add-category', { message: req.flash('success') });
});

router.post('/add-category', function(req, res, next) {
  var category = new Category();
  category.name = req.body.name;

  category.save(function(err) {
    if (err) return next(err);
    req.flash('success', 'Successfully added a category');
    return res.redirect('/add-category');
  });
})

module.exports = router;

We have to create two routes, one for get and one for post. Under the admin we will have a page that will be called add-category. In order to add a category we will render the add-category page.

When we post a new category we basically create a new instance of the object Category and we give it a name.

Next, we save the category and if there is no error then a success message will be displayed. Once the category is added the user will be redirected to the add-category page.

Of course, the module is then exported so it can be used elsewhere.

Leave a Reply