Hi, I'm Subham Maity, a software engineer. I also enjoy teaching others how to code through my tutorials. I'm always eager to learn new things and share my knowledge with the community.
⚡ I recently wrote an article on Build Your First API and wanted to share it with you all. You can find the article on my website https://codexam.vercel.app/docs/node/node1 [Better View]
⚡ I also have a repository on GitHub where you can find all the code and projects related to this topic. You can find the repository at https://github.com/Subham-Maity/node-js-full-stack-tutorial
❗ For a more in-depth look at this topic, including a detailed table of contents, check out the complete tutorial on my GitHub Repo
If you want to stay updated with my latest projects and articles, you can follow me on:
- We already know how to make a simple server. You can check it out the previous chapter
 const http = require('http');
 http.createServer((req, res) => {
   }
 ).listen(5000);
- Now res.writeHead(200, {'Content-Type': 'application/json'});- This line sets the response status code and headers using thewriteHeadmethod of theres(response) object
writeHeadmethod takes two arguments, the first is the status code and the second is an object containing the response headers (in this case, we are setting theContent-Typeheader toapplication/json)
The
writeHeadmethod is used to send the response status code and headers to the client
The status code
200is a standard HTTP status code that indicates the request was successful.
The
Content-Typeheader is used to specify the media type of the resource being sent in the response body this means that the client can expect to receive data in a specific format.
application/json, indicating that the response body will contain data in JSON format & we use/to separate the type and subtype of the media type.
- Now res.write(JSON.stringify({name: 'Subham', age: 20}));- This line writes the response body using thewritemethod of theres(response) object
The
writemethod is used to send the response body to the client means that the client can expect to receive data in a specific format.
The
JSON.stringifymethod is used to convert a JavaScript object to a JSON string
In this case, it is sending a JSON representation of an object with properties
nameandage.
The
JSON.stringifymethod takes a single argument, the object to be converted to a JSON string
- Now res.end();- This line signals the end of the response and sends it to the client using theendmethod of theres(response) object.
- The
endmethod is used to indicate that all of the response headers and body have been sent and that the server should consider this message complete.These lines of code are part of a Node.js server that sends a response to an HTTP request. The
writeHeadmethod is used to set the response status code and headers. In this case, the status code is set to200to indicate success, and theContent-Typeheader is set toapplication/jsonto indicate that the response will contain JSON data. Thewritemethod is used to send data in the response body. In this case, it sends a JSON representation of an object with propertiesnameandage. Finally, theendmethod is used to signal the end of the response and send it to the client.
const http = require('http');
http.createServer((req, res) => {
   res.writeHead(200, {'Content-Type': 'application/json'});
   res.write(JSON.stringify({name: 'Subham', age: 20}));
   res.end();
  }
).listen(5000);
- Now we can run this server using - nodemon server.jsand check it out in the browser using- localhost:5000
- Now we can see the output in the browser like this 
 
{
  "name": "Subham",
  "age": 20
}
You can also check it out in the postman we already discussed about it in this project section here
📝 Separate the data using data.js
- Create a new file data.jsand add this code
 const data ={
     "name":"Rajesh",
     "age": 20,
     "email": "rajesh@dev.com"
 }
 module.exports=data;
- Here const datais a variable which contains an object with some data- 
nameis a property of the object and its value isRajesh
- 
ageis a property of the object and its value is20
- 
emailis a property of the object and its value is `
 
- 
- 
module.exports=datais used to export the data variable so that it can be used in other files
- Now we can import this data in the server.jsfile usingrequiremethod
const data = require('./data');
- Now pass the data variable in the writemethod of theresobject insideJSON.stringifymethod like this
res.write(JSON.stringify(data));
- Now we can run this server using - nodemon server.jsand check it out in the browser using- localhost:5000
- Now we can see the output in the browser like this 
{"name":"Rajesh","age":20,"email":"rajesh@dev.com"}
📝 Add more data in the data.js file
- Now we can add more data in the data.jsfile like this
`js 
const data = [
  {
    name: "Rajesh",
    age: 20,
    address: {
      city: "Delhi",
      state: "Delhi",
      country: "India",
    },
    hobbies: ["coding", "reading", "playing"],
    skills: ["html", "css", "js", "nodejs"],
    education: {
      school: "Delhi Public School",
      college: "Delhi University",
      degree: "B.Tech",
    },
    projects: {
      project1: "Portfolio",
      project2: "Blog",
      project3: "E-commerce",
    },
    social: {
      github: "rajesh.github.io",
      linkedin: "rajesh.linkedin.com",
      twitter: "rajesh.twitter.com",
    },
    work: {
      company: "XYZ",
      position: "Software Engineer",
      experience: "2 years",
    },
    achievements: {
      achievement1: "Won a hackathon",
      achievement2: "Got a scholarship",
      achievement3: "Got a job",
    },
    interests: {
      interest1: "Reading",
      interest2: "Playing",
      interest3: "Coding",
    },
    languages: {
      language1: "English",
      language2: "Hindi",
      language3: "Punjabi",
    },
    contact: {
      phone: "1234567890",
      email: "rajesh.dev.com",
    },
  },
  {
    name: "Subham",
    age: 20,
    address: {
      city: "Delhi",
      state: "Delhi",
      country: "India",
    },
    hobbies: ["coding", "reading", "playing"],
    skills: ["html", "css", "js", "nodejs"],
    education: {
      school: "Delhi Public School",
      college: "Delhi University",
      degree: "B.Tech",
    },
    projects: {
      project1: "Portfolio",
      project2: "Blog",
      project3: "E-commerce",
    },
    social: {
      github: "subham.github.io",
      linkedin: "subham.linkedin.com",
      twitter: "subham.twitter.com",
    },
    work: {
      company: "XYZ",
      position: "Software Engineer",
      experience: "2 years",
    },
    achievements: {
      achievement1: "Won a hackathon",
      achievement2: "Got a scholarship",
      achievement3: "Got a job",
    },
    interests: {
      interest1: "Reading",
      interest2: "Playing",
      interest3: "Coding",
    },
    languages: {
      language1: "English",
      language2: "Hindi",
      language3: "Punjabi",
    },
    contact: {
      phone: "1234567890",
      email: "subham.dev.com",
    },
  },
  {
    name: "Rahul",
    age: 20,
    address: {
      city: "Delhi",
      state: "Delhi",
      country: "India",
    },
    hobbies: ["coding", "reading", "playing"],
    skills: ["html", "css", "js", "nodejs"],
    education: {
      school: "Delhi Public School",
      college: "Delhi University",
      degree: "B.Tech",
    },
    projects: {
      project1: "Portfolio",
      project2: "Blog",
      project3: "E-commerce",
    },
    social: {
      github: "rahul.github.io",
      linkedin: "rahul.linkedin.com",
      twitter: "rahul.twitter.com",
    },
    work: {
      company: "XYZ",
      position: "Software Engineer",
      experience: "2 years",
    },
    achievements: {
      achievement1: "Won a hackathon",
      achievement2: "Got a scholarship",
      achievement3: "Got a job",
    },
    interests: {
      interest1: "Reading",
      interest2: "Playing",
      interest3: "Coding",
    },
    languages: {
      language1: "English",
      language2: "Hindi",
      language3: "Punjabi",
    },
    contact: {
      phone: "1234567890",
      email: "rahul.dev.com",
    },
  },
];
module.exports = data;
`
- Now our server will look like this
`js 
const http = require('http');
const data = require('./data');
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'application/json'});
   res.write(JSON.stringify(data));
   res.end();
  }
).listen(5000);
`
- Now we can run this server using - nodemon server.jsand check it out in the browser using- localhost:5000
- Now we can see the output in the browser like this 
[{"name":"Rajesh","age":20,"address":{"city":"Delhi","state":"Delhi","country":"India"},"hobbies":["coding","reading","playing"],"skills":["html","css","js","nodejs"],"education":{"school":"Delhi Public School","college":"Delhi University","degree":"B.Tech"},"projects":{"project1":"Portfolio","project2":"Blog","project3":"E-commerce"},"social":{"github":"rajesh.github.io","linkedin":"rajesh.linkedin.com","twitter":"rajesh.twitter.com"},"work":{"company":"XYZ","position":"Software Engineer","experience":"2 years"},"achievements":{"achievement1":"Won a hackathon","achievement2":"Got a scholarship","achievement3":"Got a job"},"interests":{"interest1":"Reading","interest2":"Playing","interest3":"Coding"},"languages":{"language1":"English","language2":"Hindi","language3":"Punjabi"},"contact":{"phone":"1234567890","email":"rajesh.dev.com"}},{"name":"Subham","age":20,"address":{"city":"Delhi","state":"Delhi","country":"India"},"hobbies":["coding","reading","playing"],"skills":["html","css","js","nodejs"],"education":{"school":"Delhi Public School","college":"Delhi University","degree":"B.Tech"},"projects":{"project1":"Portfolio","project2":"Blog","project3":"E-commerce"},"social":{"github":"subham.github.io","linkedin":"subham.linkedin.com","twitter":"subham.twitter.com"},"work":{"company":"XYZ","position":"Software Engineer","experience":"2 years"},"achievements":{"achievement1":"Won a hackathon","achievement2":"Got a scholarship","achievement3":"Got a job"},"interests":{"interest1":"Reading","interest2":"Playing","interest3":"Coding"},"languages":{"language1":"English","language2":"Hindi","language3":"Punjabi"},"contact":{"phone":"1234567890","email":"subham.dev.com"}},{"name":"Rahul","age":20,"address":{"city":"Delhi","state":"Delhi","country":"India"},"hobbies":["coding","reading","playing"],"skills":["html","css","js","nodejs"],"education":{"school":"Delhi Public School","college":"Delhi University","degree":"B.Tech"},"projects":{"project1":"Portfolio","project2":"Blog","project3":"E-commerce"},"social":{"github":"rahul.github.io","linkedin":"rahul.linkedin.com","twitter":"rahul.twitter.com"},"work":{"company":"XYZ","position":"Software Engineer","experience":"2 years"},"achievements":{"achievement1":"Won a hackathon","achievement2":"Got a scholarship","achievement3":"Got a job"},"interests":{"interest1":"Reading","interest2":"Playing","interest3":"Coding"},"languages":{"language1":"English","language2":"Hindi","language3":"Punjabi"},"contact":{"phone":"1234567890","email":"rahul.dev.com"}}]
Status Code
If I send instead of 200, I send 404, it will show not found in the postman status code because there are lots of status codes are there. We use them according to our need.
Some of the status codes are:
- 200 - OK
- 201 - Created
- 204 - No Content
- 400 - Bad Request
- 401 - Unauthorized
- 403 - Forbidden
- 404 - Not Found
- 500 - Internal Server Error
- 503 - Service Unavailable
You can check all the status codes here
 
 
              
 
    
Top comments (0)