Node.js Express学习笔记
Building RESTful API’s Using Express
RESTful Services
REST: Representational State Transfer
CURD operations: Create, Read, Update, Delete
HTTP Methods: GET, POST, PUT, DELETE
Express intro
Code without express:
const http = require('http');
const server = http.createSever((req, res) => {
if (req.url === '/') {
res.write('hello World');
res.end();
}
if (req.url === '/api/courses') {
res.write(JSON.stringify([1,2,3]));
res.end();
}
});
server.listen(3000);
const express = require('express');
const app = express();
app.get('/', (req, res) => { // define a route
res.send('Hello World')
})
app.get('/api/courses', (req, res) => { // define another route
res.send([1,2,3]);
});
app.listen(3000, () => consle.log('listening on 3000'))
app.post()
app.put()
app.delete()
Nodemon
Node monitor, a tool that restarts our program when changes happen.
Environment Variable
const port = process.env.PORT || 3000;
app.listen(port, () =>console.log(`listening on port ${port}...`));
Route Parameters
app.get('/api/courses/:id/:month', (req, res) => {
// :xx is the request params, we also have query parameters
res.send(req.paras.id);
res.send(req.paras.quert);
});
Handling HTTP GET & POST requests
const express = require('express');
const app = express();
app.use(express.json()); //a piece of middleware
const courses = [
{ id: 1, name: 'course1' }
{ id: 2, name: 'course2' }
{ id: 3, name: 'course3' }
];
app.get('/', (req, res) => { // define a route
res.send('Hello World')
})
app.get('/api/courses', (req, res) => { // define another route
res.send(courses);
});
app.get('/api/courses/:id', (req, res) => {
const course = courses.find( c => c.id === parseInt(req.params.id);
if (!course) res.status(404).send('course not found')// 404, means not found
else res.send(course);
});
//Handling POST request
app.post('/api/courses', (req, res) => {
const course = {
id: courses.length + 1,
name: req.body.name
}
courses.push(course);
res.send(course);
});
const port = process.env.PORT || 3000;
app.listen(port, () =>console.log(`listening on port ${port}...`));
We can use Postman to test the endpoint.
Input Validation (use joi package)
待填。。。
Express ( Advanced Topics)
Middleware function
eg. Route handler, take request, return a response, or pass to other middleware function
request processing pipeline.
app.use(express.json());
App.use(function(req,res, next) {
consle.log(‘Logging…’);
next();
}
Build-in Middleware
app.use(express.json());
app.use(express.urlencoded()); //key=value&key=value
app.use(express.static('public'));
Third-party Middleware
helmet
morgan
Environment
develop environment? or production environment. We need to know what environment we are working on. We will enable or disable certain features.
process.env.NODE_ENV //undefined
app.get('env');
Configuration
rc config package
Debugging
const xxx = requir('debug')('name of the dbfunction')
export DEBUG=…
Templating Engines
return html markup to the client
Templating Engines: pug Mustache EJS …
app.set('view engine', 'pug')
app.set('views','./view') //default
app.get('/', (req, res) => {
res.render('index', {title: 'My Express App', message: 'Hello'};
}
)
file: index.pug
html
head
title = title
body
h1= message
Database Integration
Authentication
Asynchronous javaScript
eg. setTimeout(). schedule a mission in the future
Patterns for Dealing with Asynchronous Code
When asynchronous haven’t finished, we can not get access to it in the mean program, so how could we deal with it?
Three patterns: Callbacks, Promises, Async/await
Callbacks
callback is a function, we call when the result of asynchronous operation is ready.
It may cause “callback hell”, we can name the functions to rescue it.
Promise
Promise: an object that holds the eventual result of an asynchronous operation.
States :pending -> fulfilled(resolved) /rejected
const p = new Promise((resolve,reject) => {
//kick off some async work
//...
resolve(1);
//reject(new Error('message'));
})
p
.then(result => console.log())
.catch(err => console.log(err.message))
replace callback to promise
creating settled promises
const p = Promise.resolve( { id:1 })
p.then(result => ......)
Parallel Promises
const p1 = new Promise((resolve) => {
setTimeout(() => {
console.log('Async operation 1...');
resolve(1);
},2000)
});
const p2 = new Promise((resolve) => {
setTimeout(() => {
console.log('Async operation 2...');
resolve(1);
},2000)
});
Promise.all([p1,p2]) // Promise.race()
.then(result => ......)
.catch();
Async and Await
Keyword async
and await
can write asynchronous code in a simple form like synchronous. And need be wrapped with try catch.
async function displayCommits() {
try {
const user = await getUser(1);
const repos = await getReponsitories(user.gitHubUsername);
const commits = await getCommits(repos[0]);
console.log(commits);
}
catch(err) {
console.log('Error', err.message);
}
}
displayCommits();