The http Module
Part of the Express Basics section of Coddy's Node.js journey. Lesson 2 of 23.
Express does work for you that you cannot see. Node's own node:http module, which Express is built on, shows it.
import http from 'node:http';
const server = http.createServer((req, res) => {
if (req.url === '/repairs') {
res.statusCode = 503;
res.end('Repairs are closed today');
return;
}
res.end('Welcome to the bike shop');
});
server.listen(3000);Node calls the function for every request. There are no routes: you compare req.url, the path that was asked for, yourself. res.statusCode is the status code, a number that says how it went: 200 means OK, 404 means not found. res.end sends the body and finishes the response, so set the status before it.
Challenge
EasyBefore going further with Express, you write a tiny server with Node's own node:http module, to see the work Express does for you.
- In
server.js, inside the function given tohttp.createServer, look atreq.url. When it is/, send the textHome. - For every other path, set the status code to 404 and send the text
Not found. Set the status before you send. Once the response has ended, its status cannot change.
Try it: Press Run and send /. You should see Home with status 200. Send /nope, then /recipes/today. Both should show Not found with status 404. In lesson 1, Express sent this 404 for you; here you write it yourself.
Try it yourself
import http from 'node:http';
const server = http.createServer((req, res) => {
// Answer / with Home, and every other path with 404 Not found.
res.end('Hello from Node');
});
server.listen(3000, () => {
console.log('Listening on port 3000');
});
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Express Basics
Practice on your own: Express playground