티스토리 뷰

[ Query String이란 ]


사용자가 path(페이지 경로)를 가지고 페이지에 접근했을 때 상황에 따라 다른 모습을 보여준다면 더 다채로운 웹사이트를 구축할 수 있겠죠. 그것을 가능하게 하는 것이 Query String입니다. (URL = 'http://' + 'ip' +'path' + 'query string'으로 구성됩니다.) 즉, Query String에 따라 같은 페이지(같은 path)에서 다른 내용을 볼 수 있는 것입니다. Query String은 

<http://localhost:3000/topic?id=0>와 같은 url에서 ?id=0 부분을 말합니다. id=0, id=1, id=2...에 따라서 topic 페이지의 내용이 바뀌는 겁니다.

그럼 Query String에 따라 page의 내용이 바뀌는 모습을 확인해 보겠습니다.


const express = require('express');
const app = express();

//Query string
app.get('/topic',function(req,res){
//Current query string = req.query.id
//id에 맞는 text을 list에 저장
const contents = [
'This is first ID', //contents[0]
'This is second ID', //contents[1]
'This is third ID' //contents[2]
];

//id에 따라서 다른 문자를 출력한다.
res.send(contents[req.query.id]);
})

//port listen
app.listen(3000, function(){
console.log('Connected 3000 port');
})


<http://localhost:3000/topic?id=1> 페이지에서 Query string id는 1입니다. id가 1,2,3 일 때 각각 다른 문자를 출력하도록 했습니다. Query string "ID"를 받아오는 명령어는


req.query.id


입니다. (query string이 id가 아닌 name 변수를 갖고 있을 때는 name으로 바꾸면 됩니다.) 페이지의 query string을 받아와서 배열에 저장해 놓은 contents를 불러올 수 있습니다. 이제 <http://localhost:3000/topic?id=1>, <http://localhost:3000/topic?id=2>, <http://localhost:3000/topic?id=3> 으로 요청을 보내면 다른 내용을 보여줍니다.

이제 html 태그를 넣어서 링크를 누르면 이 topic페이지에서 3가지의 contents가 바뀌도록 해보겠습니다.


const express = require('express');
const app = express();

//Query string
app.get('/topic',function(req,res){
//Current query string = req.query.id
//id에 맞는 text을 list에 저장.
const contents = [
'This is first ID', //contents[0]
'This is second ID', //contents[1]
'This is third ID' //contents[2]
];

//html 태그사용
const output = `
<a href="/topic?id=0">Fist ID</a></br>
<a href="/topic?id=1">Second ID</a></br>
<a href="/topic?id=2">Third ID</a></br>
${contents[req.query.id]}
`

//id에 따라서 다른 문자를 출력한다.
res.send(output);
})

//port listen
app.listen(3000, function(){
console.log('Connected 3000 port');
})


이제 링크를 클릭하면 페이지의 query string id가 바뀌면서 다른 text를 출력하는 것을 확인할 수 있습니다.



[ Semantic URL ]


<http://localhost:3000/topic?id=1>과 같이 표현되면 많은 Query string이 있을 때, 

<http://localhost:3000/topic?id=1&name=140321&...>처럼 구조를 파악하기 힘든 일이 생깁니다. Semantic URL은 

<http://localhost:3000/topic/name=1/name_2=92/name_3=52/...>처럼 보기 쉽게 표현할 수 있습니다. 표현방법만 다를 뿐 사용법은 거의 유사합니다.


//Semantic URL
app.get('/topic/:id',function(req,res){
res.send(req.params.id);
})


위처럼 사용하고 <http://localhost:3000/topic/1>의 요청을 보내면 1을 보여줍니다.







'Web 개발 > javaScript & Node.js' 카테고리의 다른 글

Express - File System  (0) 2018.12.10
Express - Post  (0) 2018.12.09
Express - Jade  (0) 2018.12.07
Express  (0) 2018.12.07
JavaScript와 Node.js 시작하기  (0) 2018.12.05
댓글
최근에 올라온 글
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
공지사항
최근에 달린 댓글