这一部分介绍了使用express框架操作服务器的一些基础知识,包括:
- response的扩展函数,如
res.send()
发送字符串、res.sendFile()
发送文件、res.json({})
响应json对象 - 通过request获取请求数据,如
req.method
获取请求方式、req.path
获取请求路径、req.ip
获取请求方ip - 如何获得get和post方式请求的数据,详细可见《body-parser解析请求体》
- 代码风格,利用next实现操作链,在前一次操作中获取变量供下一次操作使用等
以下是这一部分习题的解答:
Introduction to the Basic Node and Express Challenges
-
1
console.log("Hello World");
Start a Working Express Server
1
2
3app.get('/root', (req, res) => {
res.send("Hello Express");
});-
1
2
3app.use('/', (req, res) => {
res.sendFile(__dirname + "/views/index.html");
}); -
1
app.use(express.static(__dirname + '/public'));
Serve JSON on a Specific Route
1
2
3app.get('/json', (req, res) => {
res.json({"message": "Hello json"});
});-
1
2
3app.get('/json', (req, res) => {
res.json(process.env.MESSAGE_STYLE=="uppercase"?{"message": "Hello json".toUpperCase()}:{"message":"Hello json"});
}); Implement a Root-Level Request Logger Middleware
1
2
3
4app.use('/', (req, res, next) => {
console.log(req.method+" "+req.path+" - "+req.ip);
next();
});Chain Middleware to Create a Time Server
1
2
3
4
5
6app.get('/now', (req, res, next) => {
req.time = new Date().toString();
next();
}, (req, res) => {
res.json({time: req.time});
});Get Route Parameter Input from the Client
1
2
3
4app.get('/:word/echo', (req, res, next) => {
res.json({echo: req.params.word});
next();
});Get Query Parameter Input from the Client
1
2
3app.get('/name', (req, res, next) => {
res.json({name: req.query.first+' '+req.query.last})
})Use body-parser to Parse POST Requests
1
2
3
4app.use(bodyParser.urlencoded({extended: false}));
app.post('/', (req, res) => {
res.json(req.body);
});-
1
2
3
4app.use(bodyParser.urlencoded({extended: false}));
app.post('/name',(req,res,next) => {
res.json({name: req.body.first+' '+req.body.last});
});