본문 바로가기

IT 인터넷/node.js

[node js]post방식 이해하기

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

앞서 보았던 form.pug 파일에서 method를 post로 변경해보자.



doctype html

html

head

meta(charset='utf-8')

body

form(action='/form_receiver' method='post')

p

input(type='text' name='title')

p

textarea(name='description')

p

input(type='submit')



이후


input -> hello

textarea -> world


라 입력하면 url 이 다음과 같다. 


http://localhost:3000/form_receiver


쿼리스트링으로 데이터를 전송하는게 아니란 뜻이다.


일단 app.js에 /form_receiver 의 포스트 경로르 추가해보자 


app.post('/form_receiver',function(req,res){

  res.send('hello post')

})


이후


http://localhost:3000/form 에서 데이터를 입력한 후 제출 버튼을 누르면


hello post가 뜬다.


그렇다면, 데이터는 어떻게 받아올까??


방식은 같다.


get 방식이 var title = req.query.title 이런식으로 가져왔다면,

post 방식은 var title = req.body.title 로 가져온다.


그렇다면 form_receiver에 가져온 데이터가 나타나도록 하면 다음과 같다. 


app.post('/form_receiver',function(req,res){

  var title = req.body.title;

  var description = req.body.description;

  res.send(title+','+description)

})


하지만 위의 코드로 변경하여 실행해보면 

Cannot read property 'title' of undefined

이라는 오류 코드가 뜬다.


맨 윗줄 title을 읽을 수 없다는 소리다.


문제는 body 때문인데, body 를 읽으려면 부수적인 작업이 필요하다.



EXPRESS API 사이트에 따르면, body를 읽기 위해선 body-parser가 있어야 한다.


npm install body-parser --save 

를 하고 


var bodyParser = require('body-parser');


바디파서 모듈을 가저온다.


그리고 이를 사용하기 위해 


app.use(bodyParser.urlencoded({ extended: true }));

를 app.js 파일에 추가한다.

이는 앞으로 이 애플리케이션을 통해 들어오는 모든 요청이 있으면 bodyParser가 제일 먼저 실행되고, bodyParser는 사용자가 post 방식으로 전송한 데이터가 있다면, req객체가 원래 가지고 있지 않았던 body라는 객체를 bodyParser가 추가한다는 뜻이다.



따라서

app.post('/form_receiver',function(req,res){

  var title = req.body.title;

  var description = req.body.description;

  res.send(title+','+description)

})

라는 코드를 읽을 수 있게 되고,



localhost:3000/form 페이지에서 


input -> a

textarea -> b 를 입력 후 제출 버튼을 누르면


localhost:3000/form_receiver 페이지로 넘어가고

화면에


a,b가 나타나는 것을 확일 할 수 있다.