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 route patterns 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
javascript
const express = require( 'express' ); const app = express(); const methodOverride = require( "method-override" ); // APP config mongoose.connect( "mongodb://localhost/restful_blog_app" ); app.set( "view engine" , "ejs" ); app.use(express.static( "public" )); app.use(methodOverride( "_method" )); // Creating the schema let blogSchema = new mongoose.Schema({ title: String, image: String, body: String, created: { type: Date, default : Date.now } }); let Blog = mongoose.model( "Blog" , blogSchema); app.listen(process.env.PORT, process.env.IP, function () { console.log( "SERVER IS RUNNING!" ); }) |
Name: INDEX
javascript
app.get( "/blogs" , function (req, res) { Blog.find({}, function (err, blogs) { if (err) { console.log( "ERROR!" ); } else { res.render( "index" , { blogs: blogs }); } }); }); |
Name: NEW
javascript
app.get( "/blogs/new" , function (req, res) { res.render( "new" ); }); |
Name: CREATE
javascript
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
javascript
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
javascript
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
javascript
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
javascript
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:
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.
Contact Us