RESTful Routes in Node.js

14 Jul, 2020
Routing: Routing is one of the most significant parts of your website or web application. Routing in Express is basic, adaptable, and robust. Routing is the mechanism by which requests (as specified by a URL and HTTP method) are routed(directed) to the code that handles them.
What is RESTful Routing?REST stands for Representational State Transfer which provides a way of mapping HTTP verbs (get, post, put, delete) and CRUD actions (create, read, update, delete) together. It is a convention for defining routes and when something follows the rest principle it is known as RESTFUL.
Instead of relying solely on the URL to indicate what site to visit, a RESTful route also depends on the HTTP verb and the URL.
This means that when your application receives an HTTP request, it introspects on that request and identifies the HTTP method and URL, connects that with a corresponding controller action that has that method and URL, executes the code in that action, and determines which response gets sent back to the client.
The internet would be a really confusing place without a convention for how to handle URLs – to delete a Facebook photo might be www.facebook.com/delete-this-photo, but on Instagram, it might be www.instagram.com/remove-this-post. Without a specific convention to follow, it would be hard to create new content, edit content, and delete it. RESTful routes provide a design pattern that allows for easy data manipulation.
For a route to be completely Restful it must do the following:
Separate the client from the server.
Not hold state between requests (i.e. all information necessary to respond to a request is available in each request: no data or state, is held by the server from request to request).
Use HTTP and HTTP methods.
Be reliable (for e.g most APIs follow the restful route pattern when specifying the process for authentication and important URLs).
There are 7 different restful routes pattern to follow when creating an application or web service that will interact with the server.
Example: For a blog website these Routes would be defined as:
Make sure you have Node, npm and mongoDB installed.
Installing the packages and creating the schema:
npm install express
npm install method-override
npm install mongoose

Filename: app.js
var express = require('express');var app = express();var methodOverride = require("method-override");  // APP configmongoose.connect("mongodb://localhost/restful_blog_app");app.set("view engine", "ejs");app.use(express.static("public"));app.use(methodOverride("_method"));  // Creating the schemavar blogSchema = new mongoose.Schema({    title: String,    image: String,    body: String,    created: {type: Date, default: Date.now}});  var Blog = mongoose.model("Blog", blogSchema);  app.listen(process.env.PORT, process.env.IP, function() {    console.log("SERVER IS RUNNING!");})
Name: INDEX
app.get("/blogs", function(req, res) {    Blog.find({}, function(err, blogs) {        if (err) {            console.log("ERROR!");        } else {           res.render("index", {blogs: blogs});         }    }); });
Name: NEW
app.get("/blogs/new", function(req, res) {     res.render("new"); });
Name: CREATE
app.post("/blogs", function(req, res) {            // create blog       Blog.create(req.body.blog, function(err, newBlog) {         if (err) {             res.render("new");         } else {             //then, redirect to the index             res.redirect("/blogs");         }     }); });
Name: SHOW
app.get("/blogs/:id", function(req, res) {    Blog.findById(req.params.id, function(err, foundBlog) {        if (err) {            res.redirect("/blogs");        } else {            res.render("show", {blog: foundBlog});        }    }) });
Name: EDIT
app.get("/blogs/:id/edit", function(req, res) {    Blog.findById(req.params.id, function(err, foundBlog) {        if (err) {            res.redirect("/blogs");        } else {            res.render("edit", {blog: foundBlog});        }    });})
Name: UPDATE
app.put("/blogs/:id", function(req, res) { req.body.blog.body = req.sanitize(req.body.blog.body)     Blog.findByIdAndUpdate(req.params.id,    req.body.blog, function(err, updatedBlog) {      if (err) {          res.redirect("/blogs");      }  else {          res.redirect("/blogs/" + req.params.id);      } });});
Name: DESTROY
app.delete("/blogs/:id", function(req, res) {   //destroy blog   Blog.findByIdAndRemove(req.params.id, function(err) {       if (err) {           res.redirect("/blogs");       } else {           res.redirect("/blogs");       }   })   //redirect somewhere});
The project structure will look like this:
This article focuses mainly on the app.js file. Styling can be done as per your preference.
Finally, after creating the routes and adding the styling as per your preference, run this on your command line:
node app.js
This was a really simple description of what RESTful routing is and what is its practical usage on websites.
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
How to connect Node.js with React.js ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React