Web frameworks
Regardless of what your web app does, it will have a lot in common with other web apps.
For instance, it will need to listen to requests from other clients and respond to them in the right way. Later on, it will also have to read and write from a database.
It doesn't make sense for us for write all this code from scratch every time we build a web app. It's takes time, effort and we might make mistakes.
You might hear this referred to as reinventing the wheel. Wherever possible, you should write the code once, then reuse it.
Introducing Express
To avoid reinventing the wheel, we're going to use a ready-made web framework called Express.
With Express, we get a lot of general-purpose functionality for free. We only need to write code specific to our own particular app.
npm
We're going to use a tool called npm to install and manage Express. npm comes bundled with Node.
Before we install Express, we need to tell npm a little about our project.
From the /my-app folder, run the following terminal command:
npm init -y
You will then be prompted for nine pieces of information. The default answers are fine, so just keep hitting enter until you see the following message:
Is this ok? (yes)
Hit enter again, and you should see the normal terminal prompt return. We've just told npm that we want it to manage the current folder for us.
In the projects explorer, you should see a new file called package.json
.
When you open the file, you should see the following:
{
"name": "my-app",
"version": "1.0.0",
"description": "",
"main": "hello.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
This is where our answers have been saved. npm uses this file to keep track of key aspects of our app, particularly the other software it depends on to run.
Installing Express
Our app is going to depend on Express. This makes Express a dependency of our app. We need to do two things:
- Download the Express code and save it in our app
- Update
package.json
so that npm knows Express is a dependency
We can do both these things with a single terminal command:
npm install --save express
This command may take a minute to complete.
Once it finishes, you will see a new section in package.json
called dependencies
. Express should be listed inside.
You will also notice a new folder called node_modules
. Any code that we install using npm gets saved in there.
Sometimes, a package-lock.json
file will also be created. You don't need to touch this file.
Part of Web servers
- Create your serverP
- Create your appP
- Node and the terminalP
- More about the terminalP
- Web frameworksP
- Using ExpressP
- Serving static files
- Views and templates
- Routing
- Real data
- Includes
- Get confident with Express
- Build your app in ExpressP