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_])组成。

  1. Route path: /users/:userId/books/:bookId
  2. Request URL: http://localhost:3000/users/34/books/8989
  3. req.params: { "userId": "34", "bookId": "8989" }
  4. app.get('/users/:userId/books/:bookId', function (req, res) {
  5. res.send(req.params) // 返回 { "userId": "34", "bookId": "8989" }
  6. })
  7. 由于连字符(-)和点(.)是按字面解释的,因此可以将它们与路由参数一起使用,以达到有用的目的。
  8. Route path: /flights/:from-:to
  9. Request URL: http://localhost:3000/flights/LAX-SFO
  10. req.params: { "from": "LAX", "to": "SFO" }
  11. Route path: /plantae/:genus.:species
  12. Request URL: http://localhost:3000/plantae/Prunus.persica
  13. req.params: { "genus": "Prunus", "species": "persica" }
  14. 要更好地控制可以由route参数匹配的确切字符串,可以在括号(())后面附加一个正则表达式:
  15. Route path: /user/:userId(\d+)
  16. Request URL: http://localhost:3000/user/42
  17. req.params: {"userId": "42"}
  18. 由于正则表达式通常是文字字符串的一部分,因此请确保\使用其他反斜杠对所有字符进行转义,例如\\d+。
  19. 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

  1. express.static(root [,options])
  2. app.use('/static', express.static('public'))

app.post

  1. app.post('/', function (req, res) {
  2. res.send('Got a POST request')
  3. })

app.put

  1. app.put('/user', function (req, res) {
  2. res.send('Got a PUT request at /user')
  3. })

app.delete

  1. app.delete('/user', function (req, res) {
  2. res.send('Got a DELETE request at /user')
  3. })

app.all

  1. app.all('/secret', function (req, res, next) {
  2. console.log('Accessing the secret section ...')
  3. next() // pass control to the next handler
  4. })

Demo

  1. // http://www.expressjs.com.cn/4x/api.html#app.get.method Express Api
  2. var express = require('express');
  3. var app = express();
  4. app.set('port', process.env.PORT || 3000);
  5. app.use(express.static(__dirname + '/public')); // 设置静态文件目录,外网可直接访问。
  6. app.get('/',function(req, res){
  7. res.type('text/plain');
  8. // res.type('text/html')
  9. res.end('Meadowlark Travel');
  10. });
  11. app.get('/about',function(req, res){
  12. res.type('text/plain');
  13. res.end('About Meadowlark Travel');
  14. });
  15. app.get('/error',function(req, res){
  16. thorw new Error("error");
  17. });
  18. app.use(function (req, res, next) {
  19. console.log('Time: %d', Date.now());
  20. next();
  21. });
  22. app.use(function(req, res){
  23. console.error('404');
  24. res.type('text/plain');
  25. res.status('404')
  26. res.end('404 - Not Found');
  27. });
  28. app.use(function(err, req, res){
  29. console.error(err.stack);
  30. res.type('text/plain');
  31. res.status('500')
  32. res.end('500 - Server Erroe');
  33. });
  34. app.listen(app.get('port'), function(){
  35. console.log(`Express started on http://localhost:${app.get('port')}; press Ctrl + c to terminate.`);
  36. });

app.route()

  1. app.route('/book')
  2. .get(function (req, res) {
  3. res.send('Get a random book')
  4. })
  5. .post(function (req, res) {
  6. res.send('Add a book')
  7. })
  8. .put(function (req, res) {
  9. res.send('Update the book')
  10. })
  1. var express = require('express')
  2. var router = express.Router()
  3. // middleware that is specific to this router
  4. router.use(function timeLog (req, res, next) {
  5. console.log('Time: ', Date.now())
  6. next()
  7. })
  8. // define the home page route
  9. router.get('/', function (req, res) {
  10. res.send('Birds home page')
  11. })
  12. // define the about route
  13. router.get('/about', function (req, res) {
  14. res.send('About birds')
  15. })
  16. module.exports = router

Express Demo

  1. "dependencies": {
  2. "express": "^4.17.1",
  3. "express-formidable": "^1.2.0",
  4. "formdata-node": "^4.0.1",
  5. "qs": "^6.10.1"
  6. }

接收formdata例子

  1. var express = require('express');
  2. var formidable = require('express-formidable');
  3. var app = express();
  4. app.set('port', process.env.PORT || 3000);
  5. app.use(formidable())
  6. app.listen(app.get('port'), function(){
  7. console.log(`Express started on http://localhost:${app.get('port')}; press Ctrl + c to terminate.`);
  8. });
  9. app.post('/post',function(req, res){
  10. console.log(req.body, req.query, req.param, req.params)
  11. console.log(req.fields, req.files)
  12. res.type('text/plain');
  13. res.end('About Meadowlark Travel');
  14. });

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.

Exporss 生成器

http://www.expressjs.com.cn/starter/generator.html