미들웨어에 대해서 알아보았으니 들어오는 요청을 어떻게 처리하고 데이터를 추출하는지 알아보자
POST
app.use('/add-product', (req, res, next) => {
console.log('In another middleware!');
res.send('<form actionn="/product" method="POST"><input type="text" name="title"><button type="submit">Add Product</button></form>');
});
(form을 회신하는데, 위는 간결하게 되어있는것을 연습했을뿐이다. 다음에 계속 배워가면서 html과 body와 같은 태그로 둘러쌓인 제대로된 코드로 연습할것이다.)
form에는 action이 필요하다. 요청을 보낼 경로인 url이 필요하다.
app.use('/add-product', (req, res, next) => {
console.log('In another middleware!');
res.send('<form actionn="/product" method="POST"><input type="text" name="title"><button type="submit">Add Product</button></form>');
});
app.use('/product', (req, res, next) => {
console.log(req.body);
res.redirect('/');
})
res.redirect는 리다이렉트를 해주는것인데 수동으로 상태코드를 설정하는것보다 간단하다. 또한 res.redirect('/');는 자동으로/경로로 리다이렉트 해준다.
위의 콘솔은 undefined가 보여진다. req가 들어오는 요청의 본문을 분석하려 하지 않기 때문이다. 때문에 분석기(parser)를 등록해야한다. 이는 일반적으로 경로처리 미들웨어 이전에 둔다.
요청이 어디로 향하든 본문 분석이 이루어지도록 하기 위해서이다.
그리고 이를 위해서 3rd party package를 설치해야한다.
npm install --save body-parser
그 후 bodyparser를 임포트 할 수 있다. 그리고 app.use에 호출하여 사용 할 수 있다.
const bodyParser = require('body-parser');
app.use(bodyParser. urlencoded({extended: false}));
그리고 urlencoded를 입력한다. 이는 옵션을 입력해 설정할 수 있지만 여기선 그럴 필요가 없다. 이 코드는 미들웨어를 등록해준다.
비표준 대상의 분석이 가능한지를 나타낸다. (parse non-default features)
그리고 다시 시작하여 /add-product로 가서 input창에 Book을 입력하면 {title : 'Book'}의 키값을 볼 수있다. (우리가 form에 작성한 형태}
app.get
app.get('/product', (req, res, next) => {
console.log(req.body);
res.redirect('/');
})
app.use대신에 app.get을 사용할 수도 있다. 기본적으로 app.use와 동일하고 같은 구문이다. Get요청에만 작동한다.
또한 POST요청을 걸러주는 app.post가 있다.
app.post('/product', (req, res, next) => {
console.log(req.body);
res.redirect('/');
})
/product로 들어가면 'Hello form Express!'가 나온다 왜냐면 get 요청이라 post요청이 뜨지 않는다.
delete, patch, put 등도 있다.