Node.js runs JavaScript code (like Python runs Python code). Express is a module written in JS, like Python modules are written in Python. One Python equivalent to Express is Flask.
We will!
Your browser on your laptop sends requests from a particular port on your laptop to a particular port on the server. We care about the latter. We run our code on a particular port and that's where the requests go.
You can only have one process listening on a particular port on a particular machine. Think of the port as a numbered door/room in a building.
Since we are all using Tempest, we need to use different ports. If we were all using our own laptops, we could all use the same port, say 8000 or 3000.
Yes, it can handle multiple concurrent requests, but they are started FCFS. They might take different amounts of time to complete.
Yes. Web servers are always listening.
I don't know what you mean by "where is their code run from". The code runs on the server machine.
MVC is an abstraction of certain software designs. I'm not sure additional abstractions help us here, but if you already are familiar with the abstraction, it might be helpful in understanding Express.
It's setting up an association (mapping) between a URL (endpoint) and a function to handle requests to that endpoint:
Things like parameterized endpoint values, form values (get or post; we'll talk about those next time), cookie values (after the break), the client URL, the time, etc.
Let's do that now. See next
app.get('/capital/:country', (req, res) => { let country = req.params.country; let city = capitals[country]; let page = '<h1>Capital</h1>'; page += `<p>${city} is the capital of ${country}</p>`; res.send(page); });
Great question. Let's go line by line. The first line sets up a handler for this parameterized URL (endpoint).
All the urls will look like /capital/something
like /capital/France
or /capital/Spain
.
The function will respond to such requests.
From the request object, we extract the country name, like France
.
We look up the capital city from our little database, like Paris
.
We create a string that includes some HTML code
We concatenate on a template string, filling in the city and country name.
We send that response to the client browser.
Let's do it now!
Yes
Yes, it's a nice way of logging that a request was completed, its status and such.
The handler function is at the end of the chain and does the custom work for this request. Almost all of our work will be on handler functions.
We will learn some middleware that will make our lives easier (say, parsing file upload requests).
Return
is part of the JS language and has special meaning for function calls.
But at a very general level, they are similar, in that information going back to the client.
The handler function can be asynchronous. Since Express is not
waiting for a return value, but for us to
invoke res.send()
or similar, it's all good. We will this very soon. Next week.