RESTful Routes in Node.js

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

filter_none

edit
close

play_arrow

link
brightness_4
code

var express = require('express');
var app = express();
var methodOverride = require("method-override");
  
// APP config
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(methodOverride("_method"));
  
// Creating the schema
var 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!");
})

chevron_right


Name: INDEX

filter_none

edit
close

play_arrow

link
brightness_4
code

app.get("/blogs", function(req, res) {
    Blog.find({}, function(err, blogs) {
        if (err) {
            console.log("ERROR!");
        } else {
           res.render("index", {blogs: blogs}); 
        }
    });
 });

chevron_right


Name: NEW



filter_none

edit
close

play_arrow

link
brightness_4
code

app.get("/blogs/new", function(req, res) {
     res.render("new");
 });

chevron_right


Name: CREATE

filter_none

edit
close

play_arrow

link
brightness_4
code

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");
         }
     });
 });

chevron_right


Name: SHOW

filter_none

edit
close

play_arrow

link
brightness_4
code

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});
        }
    })
 });

chevron_right


Name: EDIT

filter_none

edit
close

play_arrow

link
brightness_4
code

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});
        }
    });
})

chevron_right


Name: UPDATE

filter_none

edit
close

play_arrow

link
brightness_4
code

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);
      }
 });
});

chevron_right


Name: DESTROY

filter_none

edit
close

play_arrow

link
brightness_4
code

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
});

chevron_right


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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.