express route的用法
- 直接使用app.METHOD
const express = require('express');
const app = express();
app.get('/hello', (req, res) => {
console.log('in get');
res.send('Hello World');
});
app.listen(8080, () => {
console.log(`Server running at: http://localhost:8080/`);
});
- 使用router
const express = require('express');
const app = express();
const router = express.Router()
router.get('/hello', (req, res) => {
console.log('in get');
res.send('Hello World');
});
app.use('/', router);
app.listen(8080, () => {
console.log(`Server running at: http://localhost:8080/`);
});
这里需要注意的是'app.use('/', router)'使用根目录,然后在router里面是根据此根目录的相对目录的,所以客户端访问地址是:localhost:8080/hello
,而如果使用app.use('/hello', router);
,则客户端访问地址是:localhost:8080/hello/hello
通常我们会把router放到一个独立的模块里:
$ cat router.js
const express = require('express');
const router = express.Router()
router.get('/hello', (req, res) => {
console.log('in get');
res.send('Hello World');
});
router.get('/hello2', (req, res) => {
console.log('in get2');
res.send('Hello World');
});
module.exports = router
然后在index.js里面调用:
$ cat index.js
const express = require('express');
const app = express();
const router = require('./router.js');
app.use('/', router);
app.listen(8080, () => {
console.log(`Server running at: http://localhost:8080/`);
});
客户端可以调用localhost:8080/hello
,和localhost:8080/hello2
。
- 是app.route()
const express = require('express');
const app = express();
app.route('/hello')
.all(function (req, res, next) {
console.log('in all');
next()
// runs for all HTTP verbs first
// think of it as route specific middleware!
})
.get(function (req, res, next) {
console.log('in get');
res.send('Hello World');
})
.post(function (req, res, next) {
console.log('in post');
res.send('Hello World');
})
app.listen(8080, () => {
console.log(`Server running at: http://localhost:8080/`);
});
这样的好处是只写一个route如果支持不同的方法。
网友评论