반응형
routes 라는 폴더생성. 그안에 admin.js와 shop.js 생성
웹 사이트를 운영한다고 했을때, admin에는 /product를, shop.js에는 기본경로/를 넣는다.
<admin.js>
//실행하게될 함수
const router = express.Router();
router.get('/add-product', (req, res, next) => {
res.send(
'<form action="/product" method="POST"><input type="text" name="title"><button type="submit">Add Product</button></form>'
);
});
router.post('/product', (req, res, next) => {
console.log(req.body);
res.redirect('/');
});
//router객체는 위의 get과 post 루트들이 등록되어있다.
module.exports = router;
const router은 r 도 R도 가능하지만 express.Router();에는 R은 꼭 대문자로 써주어야한다.
<shop.js>
(직접만들어봤는데, 임포트하고 express.Router호출까지만 가능했다.
get과 module.exports도 다음부터 꼭 스스로 넣길....)
const express = require('express');
const router = express.Router();
router.get('/', (req, res, next) => {
res.send('<h1>Hello from Express!</h1>');
});
module.exports = router;
<app.js>
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
//routes의 상대경로를 나타낸다. js는 자동으로 추가되므로 생략 가능하다.
//임포트하는 routes들의 순서는 중요하지 않다.
const adminRoutes = require('./routes/admin');
const shopRoutes = require('./routes/shop');
app.use(bodyParser.urlencoded({extended: false}));
//함수처럼 호출하지 않고 괄호없이 객체자체를 입력해준다. admin.js를 내보낸 router객체이다.
따라서 요청을 처리할때 자동으로 admin.js 파일의 라우트를 고려한다.
//순서가 중요하다.
//shopRoutes와 adminRoutes의 순서를 바꾸면 제대로 작동한다. 그리고 shop.js의 get라우트로 가지 않는다.
//이건 get을 사용했기 때문이다.
app.use(adminRoutes);
app.use(shopRoutes);
app.listen(3000);
about get and post
: get 과 post 등은 경로와 정확히 일치하는 요청만을 처리한다. 모든 http mothod를 처리하는 use를 사용한채로(shop.js에 router.use로 바꾼다면) 다시 불러온다면 내가 적은 Hello from Express! 가 보이게 된다.
따라서 이 매칭은 router를 통해서가 아니라 get 을 통해서 이루어진다. app.js 파일에서 했어도 동일한 결과를 볼 수 있다.
따라서 get은 get method임을 확인할 뿐만아니라 정확히 경로임을 확인 할 수 있다.
주의!
//**순서가 중요하다. app.use(adminRoutes);를 /미들웨어 후에 두면 절대 도달하지 못한다.
//아래와 같이 두면 안된다는것을 반드시 유념하길
router.get('/', (req, res, next) => {
res.send('<h1>Hello from Express!</h1>');
});
app.use(adminRoutes);