본문 바로가기

Nodejs

[Node.js] url 해부하기(query, params), Form으로 데이터 전달

url 해부하기 

ex) http://a.com/topic?id=1

  • http : 프로토콜
  • a.com : 도메인. 서버 컴퓨터가 위치하는 주소 
  • topic : path. directory명 또는 router와 연결되는 주소
  • id = 1 : query string

url req이 들어오면 해당하는 router에 걸려 res를 해준다. <=> url에 해당하는 router가 없다면 404 에러가 뜬다. 

 

query 객체사용법 

query를 통해 사용자가 query string으로 요청한 정보를 사용할 수 있다. 

//http://a.com/topic?name=Baeji   			 => 출력 : Baeji
app.get('/topic', function(req, res){
	res.send(req.query.name);
})

//http://a.com/topic?id=1		 		 => 출력 : 1
app.get('/topic', function(req, res){
	res.send(req.query.id);
})


//http://a.com/topic?id=1&name=Baeji 		 	=> 출력 : 1,Baeji
app.get('/topic', function(req, res){
	res.send(req.query.id+','+req.query.name);
})

 

 

 

 

 

Semantic url : 쿼리 스트링 없이 깔끔하게 url만들기 

path방식(시멘틱 url)을 통해 들어오는 요청은 params로 요청한 정보를 사용할 수 있다. 

  • http://a.com/topic?id=1   => http://a.com/topic/1
//http://a.com/topic/1             			  => 출력 : 1
app.get('/topic/:id', function(req,res){
	const output = ${req.params.id}}
    res.send(output);
})

//http://a.com/topic/Baeji				 => 출력 : Baeji
app.get('/topic/:name', function(req,res){
	const output = ${req.params.name}}
    res.send(output);
})

//http://a.com/topic/100/edit 				 => 출력 : 100,edit
app.get('/topic/:id/:mode', function(req,res){
    res.send(${req.params.id}+','+${req.params.mode});
})

 

 

 


url과 Form[Post,Get]을 이용한 정보 전달

get방식

//app.js
app.get('/form_receiver',function(req,res){
	const title = req.query.title;
    res.send(title);
})

//form.jade
doctype html
html 
    body
    	form(action = '/form_receiver', method='get')
        	p
            	input(type = "text" name = 'title)

 

post방식

body-parser 필요: post방식으로 전송한 data를 우리 application에서 사용할 수 있도록 하는 플러그인 ( =미들웨어 )

//app.js
app.post('/form_receiver',function(req,res){
    const title = req.body.title;
    res.send(title);
})


//form.jade
doctype html
html 
    body
    	form(action = '/form_receiver'. method='post')
        	p
            		input(type = "text" name = 'title')
            	p 
            		textarea(name = 'desc')
           	p
            		input(type="submit")

 

body-parser 설치 

npm install body-parser  --save
//app.js
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended:false}))
더보기

use 메소드로 bodyParser가 app앞에 붙어 url요청이 들어올때마다 bodyParser를 거치게 된다. 

원래는 req에 body가 없었기때문에 에러가 났지만 bodyParser가 req에 body객체를 만들어 그 속에 프로퍼티 title을 추가해준다. 그 결과 post방식을 사용할 수 있다. 

 

 

GET / POST는 언제?

GET

  • 데이터가 url에 노출돼도 괜찮을 때 
  • 서버에 전송되는 데이터의 용량이 작을 때

POST

  • 데이터가 url에 노출되면 안 될 때 (id와 password)
  • 서버에 전송되는 데이터의 용량이 클 때