http://www.expressjs.com.cn/4x/api.html#app.get.method Express Api
npm install —save express
Exporss Hello World
app.get
app.get(name) 方法,app.get(path, callback [, callback …])不是同一个方法
app.get(path, callback [, callback …])是添加路由的方法,路由默认忽略大小写或反斜杠并且进行匹配时也不考虑查询字符串
/About,/about,/about?foo=bar,/about/?foo=bar
路径参数的名称必须由“单词字符”([A-Za-z0-9_])组成。
Route path: /users/:userId/books/:bookIdRequest URL: http://localhost:3000/users/34/books/8989req.params: { "userId": "34", "bookId": "8989" }app.get('/users/:userId/books/:bookId', function (req, res) {res.send(req.params) // 返回 { "userId": "34", "bookId": "8989" }})由于连字符(-)和点(.)是按字面解释的,因此可以将它们与路由参数一起使用,以达到有用的目的。Route path: /flights/:from-:toRequest URL: http://localhost:3000/flights/LAX-SFOreq.params: { "from": "LAX", "to": "SFO" }Route path: /plantae/:genus.:speciesRequest URL: http://localhost:3000/plantae/Prunus.persicareq.params: { "genus": "Prunus", "species": "persica" }要更好地控制可以由route参数匹配的确切字符串,可以在括号(())后面附加一个正则表达式:Route path: /user/:userId(\d+)Request URL: http://localhost:3000/user/42req.params: {"userId": "42"}由于正则表达式通常是文字字符串的一部分,因此请确保\使用其他反斜杠对所有字符进行转义,例如\\d+。在Express 4.x中,不以常规方式解释正则表达式中的*字符。解决方法是使用{0,}代替*。这可能会在Express 5中修复。
app.use
app.use([path,] callback [,callback …]) 也是一个添加路由的方法, 每个请求都将执行没有路径安装的中间件。
app.use(‘/abcd’, function (req, res, next) { 这将匹配以/ abcd开头的路径
app.use(‘/abc?d’, function (req, res, next) { 这将匹配以/ abcd和/ abd开头的路径
app.use(‘/ab+cd’, function (req, res, next) { 这将匹配以/ abcd,/ abbcd,/ abbbbbcd开头的路径
app.use(‘/ab*cd’, function (req, res, next) { 这将匹配以/ abcd,/ abxcd,/ abFOOcd,/ abbArcd开头的路径
app.use(‘/a(bc)?d’, function (req, res, next) { 这将匹配以/ ad和/ abcd开头的路径:
app.use(/\/abc|\/xyz/, function (req, res, next) { 这将匹配以/ abc和/ xyz开头的路径
app.use([‘/abcd’, ‘/xyza’, /\/lmn|\/pqr/], function (req, res, next) { 这将匹配以/ abcd,/ xyza,/ lmn和/ pqr开头的路径
中间件功能按顺序执行,因此中间件包含的顺序很重要。
next参数可以让路由继续执行
app.use(express.static(__dirname + ‘/public’)); // 设置静态文件目录,外网可直接访问。
app.use(function(req, res, next) { // 第一个路由
res.send(‘www’);
next();
});
这个中间件不允许请求超过他
app.use(function(req, res, next) { // 第二个路由
console.log(‘不允许2次send’)
});
将永远不会到达这里
app.get(‘/‘, function (req, res) { // 第三个路由
console.log(‘将永远不会到达这里’)
res.send(‘Welcome’);
});
如果发生error会执行这个
app.use(function(err, req, res){
console.error(err.stack);
res.type(‘text/plain’);
res.status(‘500’)
res.end(‘500 - Server Erroe’);
});
express.static
express.static(root [,options])app.use('/static', express.static('public'))
app.post
app.post('/', function (req, res) {res.send('Got a POST request')})
app.put
app.put('/user', function (req, res) {res.send('Got a PUT request at /user')})
app.delete
app.delete('/user', function (req, res) {res.send('Got a DELETE request at /user')})
app.all
app.all('/secret', function (req, res, next) {console.log('Accessing the secret section ...')next() // pass control to the next handler})
Demo
// http://www.expressjs.com.cn/4x/api.html#app.get.method Express Apivar express = require('express');var app = express();app.set('port', process.env.PORT || 3000);app.use(express.static(__dirname + '/public')); // 设置静态文件目录,外网可直接访问。app.get('/',function(req, res){res.type('text/plain');// res.type('text/html')res.end('Meadowlark Travel');});app.get('/about',function(req, res){res.type('text/plain');res.end('About Meadowlark Travel');});app.get('/error',function(req, res){thorw new Error("error");});app.use(function (req, res, next) {console.log('Time: %d', Date.now());next();});app.use(function(req, res){console.error('404');res.type('text/plain');res.status('404')res.end('404 - Not Found');});app.use(function(err, req, res){console.error(err.stack);res.type('text/plain');res.status('500')res.end('500 - Server Erroe');});app.listen(app.get('port'), function(){console.log(`Express started on http://localhost:${app.get('port')}; press Ctrl + c to terminate.`);});
app.route()
app.route('/book').get(function (req, res) {res.send('Get a random book')}).post(function (req, res) {res.send('Add a book')}).put(function (req, res) {res.send('Update the book')})
var express = require('express')var router = express.Router()// middleware that is specific to this routerrouter.use(function timeLog (req, res, next) {console.log('Time: ', Date.now())next()})// define the home page routerouter.get('/', function (req, res) {res.send('Birds home page')})// define the about routerouter.get('/about', function (req, res) {res.send('About birds')})module.exports = router
Express Demo
"dependencies": {"express": "^4.17.1","express-formidable": "^1.2.0","formdata-node": "^4.0.1","qs": "^6.10.1"}
接收formdata例子
var express = require('express');var formidable = require('express-formidable');var app = express();app.set('port', process.env.PORT || 3000);app.use(formidable())app.listen(app.get('port'), function(){console.log(`Express started on http://localhost:${app.get('port')}; press Ctrl + c to terminate.`);});app.post('/post',function(req, res){console.log(req.body, req.query, req.param, req.params)console.log(req.fields, req.files)res.type('text/plain');res.end('About Meadowlark Travel');});
Response methods
The methods on the response object (res) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.
| Method | Description |
|---|---|
| res.download() | Prompt a file to be downloaded. |
| res.end() | End the response process. |
| res.json() | Send a JSON response. |
| res.jsonp() | Send a JSON response with JSONP support. |
| res.redirect() | Redirect a request. |
| res.render() | Render a view template. |
| res.send() | Send a response of various types. |
| res.sendFile() | Send a file as an octet stream. |
| res.sendStatus() | Set the response status code and send its string representation as the response body. |
