본문 바로가기

IT 인터넷/node.js

[node js]get 방식 이해하기

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

get 방식은 앞서 공부했던 쿼리스트링을 통해 데이터를 가져오는 방식이다.


get방식을 공부하기 위한 세팅을 먼저 해보자.


get 방식을 위해 views 파일 밑에 form이라는 pug 파일이 로드될 수 있도록 세팅한다.


app.get('/form',function(req,res){

res.render('form')

})


이제 form.pug 파일을 만든다.


doctype html

html

head

meta(charset='utf-8')

body

form(action='/form_receiver')

p

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

p

textarea(name='description')

p

input(type='submit')



이렇게 한 후 


localhost:3000/form 을 로드하면


input 입력창 , textarea 입력창, 제출 버튼이 생긴다.


input: hello

textarea: world


라 입력하고 enter를 누르면 /form_receiver라는 페이지로 이동한다.


아직 페이지가 없어 호출하지 못했지만, url이 다음과 같다.

http://localhost:3000/form_receiver?title=hello&description=world


쿼리스트링으로 데이터를 넘기는 것이다.


form.pug 파일에 method를 입력해보면



doctype html

html

head

meta(charset='utf-8')

body

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

p

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

p

textarea(name='description')

p

input(type='submit')


결과는 똑같다. form태그의 default 방식은 get임을 알 수 있다. 



아직 /form_receiver 라는 페이지를 만들지 않았기 때문에 app.js로 돌아가 만들어보자


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

var title = req.query.title;

var description = req.query.description;

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

})


를 입력한 후 form.pug에 


input: hello

textarea: world


을 입력하면


hello,world 라는 내용이 뜬다.