HTTP Request and Response Explained

Think of being at a restaurant. When you, as a customer, order food, you are making a request. In web development, a request happens when your browser (the client) asks a server for information or to do something.

When you type a URL in your browser or click a link, you send a request to a web server. This request can be for a webpage, to submit a form, or to get data from an API.

Engaging Example: The Pizza Order

Let’s break this down with a fun example:

  1. The Request: You go into a pizza shop and say, “I’d like a pepperoni pizza, please!” This is your request for that specific pizza.
  2. The Server: The server takes your order and goes to the kitchen. This is like the server processing your request.
  3. The Response: After a while, the chef makes your pizza and returns it to the server, who brings it to you. This is like the server responding with the information you wanted—your delicious pizza!

Code Example: Handling a Request in Node.js

Now, let’s see how we can show this with a simple code example in Node.js:

javascript

Copy code

const http = require(‘http’);

const server = http.createServer((req, res) => {

    res.setHeader(‘Content-Type’, ‘text/plain’);

    // Handle a specific request

    if (req.method === ‘GET’ && req.url === ‘/pizza’) {

        res.statusCode = 200;

        res.end(‘Your order for a pepperoni pizza has been received! Enjoy your meal!’);

    } else {

        res.statusCode = 404;

        res.end(‘Sorry, we don’t have that on the menu!’);

    }

});

const PORT = 3000;

server.listen(PORT, () => {

    console.log(`Server is running on http://localhost:${PORT}`);

});

Explanation of the Code

  • Creating the Server: We make a simple HTTP server using Node.js.
  • Handling Requests: When someone requests /pizza, the server confirms the order. If they ask for something else, it responds with a “404 Not Found” message, like saying, “We don’t have that on the menu!”

Summary

In short, an HTTP request is like ordering food at a restaurant. The client (you) asks for something specific, and the server (restaurant) prepares and serves it. This is how communication on the web works, making it easy for clients and servers to talk to each other!

Working with Requests in Node.js

When we handle requests in Node.js, we use something called the req object. 

This object gives us important information about what the client is asking for.

  • Getting the URL: You can find out which URL the client is requesting by using req.url. This tells you what the client wants to see.
  • Using Headers: You can also check the request headers with req.headers. Headers give us extra details about the request, like what kind of data it is.

Setting the Content Type

One important header we often need to set is Content-Type. This tells the client what type of data we are sending back. For example, if we want to send HTML content, we set the Content-Type to text/html.

You can do this by using:

javascript

Copy code

res.setHeader(‘Content-Type’, ‘text/html’);

Handling Multiple Endpoints in Node.js

Let’s see how to check the URL and respond with HTML content. We’ll make our server give different messages based on the URL the client asks for.

  1. Check the URL: First, we’ll see if req.url is /. If it is, we’ll respond with “Hello, World!”
  2. For returning we will use the response object and then return it .
  3. Add More Endpoints: We’ll add another endpoint, /pizza, which will return “This is your pizza.”
  4. Understanding statusCode: The statusCode shows the result of the request. For example, 200 means everything is okay. 404 means the page was not found.

For any other URL, we respond with “404 Not Found” and set the status code to 404.

Summary

In this example, we learned to check the URL and respond with HTML content. We added endpoints like /pizza to give specific responses. The statusCode helps us show if the request was successful or if there was a problem.

Enroll in Sharpener NOW !

At Sharpener Tech, we don’t just teach, we transform careers! Our Pay After Placement model ensures ZERO financial risk you pay only when you land a high-paying job. With industry-driven Full Stack Development training, hands-on projects, and expert mentorship, we guarantee your success in the tech world. Don’t just dream BUILD your future with Sharpener Tech!  Apply now and start your journey!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *