node.js router
1. router 기본 샘플코드
1 | var express = require('express'); |
test 해보기
- localhost:3005/user/r1
- localhost:3005/user/r1
- localhost:3005/account/r1
- localhost:3005/account/r1
2. 위의코드 이쁘게 나누보자
- app.js가 실행되어지고 있는 폴더에서 폴더 생성 mkdir routes
- cd routes
vim account.js
1
2
3
4
5
6
7
8
9
10
11var express = require('express');
var accountRouter = express.Router();
accountRouter.get('/r1', function(req, res){
res.send('/account/r1');
});
accountRouter.get('/r2', function(req, res){
res.send('/account/r2');
});
module.exports = accountRouter;vim user.js
1
2
3
4
5
6
7
8
9
10var express = require('express');
var userRouter = express.Router();
userRouter.get('/r1', function(req, res){
res.send('user/r1');
});
userRouter.get('/r2', function(req, res){
res.send('user/r2');
});
module.exports = userRouter;app.js수정
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15var express = require('express');
var app = express();
var accountRouter = require('./routes/account.js')
app.use('/account', accountRouter);
//account로 들어오는 모든 경로를 accountRouter에 위임
var userRouter = require('./routes/user.js')
app.use('/user', userRouter);
//user 들어오는 모든 경로를 userRouter 위임
app.listen(3005, function(){
console.log('3005 port connected');
});test 해보기
- localhost:3005/user/r1
- localhost:3005/user/r1
- localhost:3005/account/r1
- localhost:3005/account/r1