🎓 A1Learner
🔍
0 of 50 lessons completed

Requests and Responses

A request is a note from a visitor asking for something. A response is the reply the server sends back.

Read the kind of request

This line prints the method, such as GET.

console.log(req.method);

Read the address asked for

This line prints the address, such as /about.

console.log(req.url);

Example

const http = require('http');

const server = http.createServer((req, res) => {
  console.log(req.method);
  console.log(req.url);
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello!');
});

server.listen(3000, () => {
  console.log('Server running on port 3000');
});

Key points

  • Every visit sends one request to the server.
  • req stands for the request inside the server function.
  • req.method names the kind of request, such as GET.
  • GET is a request that asks for a page.
  • req.url names the address the visitor asked for.
  • A URL is the address of a page on the web.
  • res stands for the response, the reply the server sends.
  • res.writeHead sets the status code and the headers of the reply.
  • A status code is a number that tells how the request went.
  • The code 200 means the request worked.
  • A header is a small label sent with a reply.
  • res.end sends the reply text and ends the reply.

In this example, the server prints the method and the address for each visit. A visit to /about prints GET and then /about. The server answers with the text Hello!. The startup line prints Server running on port 3000.

Note

The server prints the method and the address only when a visit arrives.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A visitor opens /about on your server. What does req.url hold?