Express.JS
CSE 3330 - SMU - Spring 2019
Express.JS
npm
package.json
> npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (npmexample) firstnpm
version: (1.0.0) 0.0.1
description: A first use of npm
entry point: (index.js) app.js
test command:
git repository:
keywords:
author: Mark Fontenot
license: (ISC)
package.json
{
"name": "firstnpm",
"version": "0.0.1",
"description": "A first use of npm",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Mark Fontenot",
"license": "ISC"
}
package.json
npm install express
npm install -g nodemon (may need to sudo)
{
"name": "firstnpm",
"version": "0.0.1",
"description": "A first use of npm",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Mark Fontenot",
"license": "ISC",
"dependencies": {
"express": "^4.16.4"
}
}
^ Most recent major version (4.x.x here)
~ Most recent minor version (4.16.x here)
app.js
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(port, () => {
console.log('Simple Example');
});
Handler for GET /
Start the server
app.js
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(port, () => {
console.log('Simple Example');
});
1. Type the code below into app.js.
2. execute node app.js from the command line.
3. In a browser, go to http://localhost:3000/.
4. Add a command that will print to the console “Incoming request” in the GET / event handler.
5. Re-execute the server
nodemon
nodemon app.js
Watches for changes to files and will automatically reload the file
Try it out by responding to the client with
<h1>Hello World</h1>
Express Routing
Basic format:
app.HTTPMethod(Path, Handler);
HTTPMethod can be one of a number of HTTP verbs.
Common ones: get, post, put, delete
Examples
app.get('/', function (req, res) {� res.send('Hello World!')�})
app.post('/', function (req, res) {
res.send('Got a POST request')
})
app.put('/user', function (req, res) {
res.send('Got a PUT request at /user')
})
app.delete('/user', function (req, res) {
res.send('Got a DELETE request at /user')
})