Hello, Express
Part of the Express Basics section of Coddy's Node.js journey. Lesson 1 of 20.
A web server waits for requests from browsers and apps and sends back responses. Express is the most used library for writing one in Node.js.
import express from 'express';
const app = express();
app.get('/hours', (req, res) => {
res.send('Open 9 to 5');
});
app.listen(3000);app.get('/hours', ...) is a route: what to do when someone asks for the path /hours. Express calls the function with the request req and the response res, and res.send sends the answer. Nothing goes back until it is called. app.listen(3000) starts the server on port 3000.
On a laptop you would start it with node server.js and call it from a browser or with curl. Here Run starts it and the request bar sends the requests.
Challenge
EasyMake the home page / answer Welcome to Recipe Box.
Press Run and send GET /. Then send GET /nope to see what Express answers for a path with no route.
Try it yourself
import express from 'express';
const app = express();
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.listen(3000, () => {
console.log('Recipe Box is running on port 3000');
});