Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 8994

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T06:18:08+00:00 2024-11-28T06:18:08+00:00

😎Build REST Api With Node JS Without Any Frameworks From Scrach

  • 60k

In this post we will learn how to make CRUD rest api in node js from scratch without using any frameworks such as Express,Oak,etc 😍.We will use basic node http package to build it .

🔥 Get Up And Running With Server

Firstly we will import http package from node js. Then we will call createServer() method in it which will give us an instance of http.Server class.After that we will call listen() method on that http.Server class instance which will starts the HTTP server listening for connections 😉.

const http = require('http'); const server = http.createServer(); const PORT = process.env.PORT || 5000; server.listen(PORT, () => console.log(`Server listening on port ${PORT}!!!`)); 
Enter fullscreen mode Exit fullscreen mode

About http.createServer()

http.createServer() takes a parameter requestListener which is optional.The HTTP Server object can listen to ports on your computer and execute a function, a requestListener, each time a request is made.This requestListener handles request from the user, as well as response back to the user. In this requestListener we will have access to request and response parameters. Inside this function we will check the req.url and req.method of each incoming request and then conditionally do some business logic will return desired response back to the user ✨ .

🥳 Lets build CRUD based rest api

Enough of theory , now lets discuss how we can build a simple CRUD api to manage Todos.This is the link to github repository where you will get the completed source code. In this you will need two files
which are data.js and todoController.js. In todo.js you will find dummy data used for this tutorial. Because I don't want to make things complex by adding databases and all that stuff for the sake of this tutorial. In todoController.js you will find some functions which we can perform on this data e.g. find todo by its id or get all todos like that. You are free to go through these two files.
We are going to have five routes to manage todos.

  • url:/api/todos and method:GET – route to fetch all todos.
  • url:/api/todos/:id and method:GET – route to fetch a todo by its id.
  • url:/api/todos/:id and method:PATCH – route to update a todo by its id.
  • url:/api/todos/:id and method:DELETE – route to delete a todo by its id.
  • url:/api/todos/: and method:POST – route to create a new todo.

Before writing any routes , we need to understand two methods present on res parameter of requestListener.

  1. writeHead() – This method sends an HTTP status code and a collection of response headers back to the client. The status code is used to indicate the result of the request. For example, everyone has encountered a 404 error before, indicating that a page could not be found. The example server returns the code 200, which indicates success.
  2. end() – This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response. In this method we will pass our data which we wanted to return back to user as response.

(1) route to fetch all todos.

Firstly , we will check if the url and method of incoming request is /api/todos and GET respectively.If it is the case then we will fetch all todos from data.js with the help of todoController.js and then if all goes well then we will set the status code as 200 which indicates that the request has been succesful. Here , we will also set the header as Content-Type : application/json which tells the client that the content type of the returned content is JSON format.We are going to set this header in every route and in each request we are going to convert our data to JSON string.Then if url or method of incoming request does not match , then we will set the status code as 404 which indicates NOT FOUND and we will send message that route not found as response.

const server = http.createServer(async (req, res) => {     if (req.url === '/api/todos' && req.method === 'GET') {         const todos = await Todo.findAll();         res.writeHead(200, { 'Content-Type': 'application/json' });         res.end(JSON.stringify(todos));     }   else {         res.writeHead(404, { 'Content-Type': 'application/json' });         res.end(JSON.stringify({ message: 'Route not found!' }));     } }); 
Enter fullscreen mode Exit fullscreen mode

For testing API during development you can use any client as you wish. I prefer Postman for testing my APIs. You can get it here for any platform.
get-all.jpg

(2) route to fetch a todo by its id

For this route also our procedure will be same. Only difference will be instead of fetching all todos we will fetch a single todo and return back response. In this route we will have a dynamic parameter id which will be passed into route itself and depend on which we will fetch particular todo.

if (req.url.match(//api/todos/([a-z A-Z 0-9]+)/) && req.method === 'GET') {         try {             const id = req.url.split('/')[3];             const todo = await Todo.findById(id);             res.writeHead(200, { 'Content-Type': 'application/json' });             res.end(JSON.stringify(todo));         } catch (error) {             res.writeHead(404, { 'Content-Type': 'application/json' });             res.end(JSON.stringify({ message: 'Todo not found!' }));         }     } 
Enter fullscreen mode Exit fullscreen mode

After testing we will get response like
get-one.jpg

(3) route to delete a todo by its id

In this route firstly , we will check if the req.method is DELETE
This route will be same as above route the only difference will be instead of fetching by id ,we will delete a todo by its id and send message as response to user.

if (req.url.match(//api/todos/([a-z A-Z 0-9]+)/) && req.method === 'DELETE') {         try {             const id = req.url.split('/')[3];             await Todo.deleteById(id);             res.writeHead(200, { 'Content-Type': 'application/json' });             res.end(JSON.stringify({ message: 'Todo deleted successfully!!!' }));         } catch (error) {             console.log(error);             res.writeHead(404, { 'Content-Type': 'application/json' });             res.end(JSON.stringify({ message: 'Todo not found!' }));         }     } 
Enter fullscreen mode Exit fullscreen mode

After testing it in Postman
delete-one.jpg

And that's it for this one. To see how we can create remaining two routes i.e. one for creating todo and one for updating todo , visit satishnaikawadi.me

I hope all of you understand at least to some extent what I explained in this post 😇. If any one has queries feel free to ask them.

beginnersjavascriptnodewebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.