express(路由)

配置express
路由基本方法

/**
 * 路由处理
 * http 提交方式:
 * get -- 查询
 * post -- 添加
 * put -- 修改
 * delete -- 删除
 */
 const express = require('express');
 const app = express();
 app.use('/public',express.static('public'));

app.get('/login',(req, res) => {
     res.end('get data');
 });
app.post('/login',(req, res) => {
     res.end('post data');
 });
 app.put('/login', (req, res) => {
     res.end('put data');
 });
 app.delete('/login', (req, res) => {
     res.end('delete data');
 })
 app.listen(3000, () => {
     console.log("running……");
 })

将路由合并

const express = require('express');
const app = express();

app.use(express.static('public'));

// app.all('/ab*cd',(req, res) => {
//     res.send(req.method);
// });

app.route('/login')
  .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');
  });

app.listen(3000, () => {
    console.log("running……");
})

将路由版块独立出来

const express = require('express');
const app = express();
const router = require('./router.js')  -------将路由规则全部写在router.js里面

app.use(express.static('public'));
app.use(router);

app.listen(3000, () => {
    console.log("running……");
})

const express = require('express');
const router = express.Router();

router.get('/login',(req, res) => {
    res.end("req");
});
router.post('/login',(req, res) => {
    res.end("req");
});
router.put('/login', (req, res) => {
    res.end('put data');
});
router.delete('/login', (req, res) => {
    res.end('delete data');
});
module.exports = router;

all和用正则来匹配路由(app.all是4种方式都可以)

const express = require('express');
const app = express();

app.use(express.static('public'));

app.all('/ab*cd',(req, res) => {
    res.send(req.method);
});
// 匹配 acd 和 abcd
app.get('/ab?cd', function(req, res) {
  res.send('ab?cd');
});

// 匹配 abcd、abbcd、abbbcd等
app.get('/ab+cd', function(req, res) {
  res.send('ab+cd');
});

// 匹配 abcd、abxcd、abRABDOMcd、ab123cd等
app.get('/ab*cd', function(req, res) {
  res.send('ab*cd');
});

// 匹配 /abe 和 /abcde
app.get('/ab(cd)?e', function(req, res) {
 res.send('ab(cd)?e');
});

你可能感兴趣的:(express(路由))