You can serve HTML and JS files with ExpressJS. You can also build dynamic web sites with Express JS as well.
Scenario: Serve a basic NodeJS app
Objective:
- Create a web server using Express JS
- Server simple dynamic sites using NodeJS
Steps:
-
In your Terminal / Command Prompt, create a new folder called
myapp
mkdir myapp cd myapp
-
Create a new NPM package
npm init
Use the default for everything excpet the Entry Point. Change it to
app.js
. -
Add Express JS package
npm install express --save
-
Open the
myapp
folder in Visual Studio Code. -
Create a new file called
app.js
Copy and paste the contents below into
app.js
.const express = require('express') const app = express() const port = 3000 app.get('/', (req, res) => { const name = req.query.name || 'World' res.send('Hello ' + name + '!') }) app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Remember to save the file!
-
Start the ExpressJS server
node app.js
-
Open your browser and go to: http://localhost:3000
-
Try changing the name: http://localhost:3000?name=Elisha
Further Reading
Scenario: Here's an easier way to bootstrap an ExpressJS app
Objective:
- Create a web server using Express's Generator
Steps:
-
Using Terminal or Command Prompt, create a new folder:
myapp2
mkdir myapp2 cd myapp2
-
Type this commands:
npx express-generator npm install
-
You can start the app like this:
DEBUG=myapp2:* npm start
-
Visit the site in your browser: http://localhost:3000
Further Reading