본문 바로가기

IT 인터넷/node.js

[node js]semantic URL 방식

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

앞서 쿼리스트링에 대해서 공부했다.


쿼리스트링이 달린 url을 한번 살펴보자.


http://estelar.tistory.com/form/id=3&name=yeseul 


위 url이 너무 복잡하지 않은가?


url을 간단하게 만들 수 있는 것이 semantic URL 방식이다.


예를 들어 위와 같은 코드는


http://estelar.tistory.com/form/3/yeseul 


이렇게 줄일 수 있다.



sementic url은 어떻게 사용하는 걸까??


저번시간에 봤던 코드를 살펴보자 


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

var topics = [

'javascript is',

'nodejs is',

'express is'

]


var output = `

   <a href="/topic?id=0">Javascript</a>

        <a href="/topic?id=1">Nodejs</a>

        <a href="/topic?id=2">Express</a>

        <h1>${topics[req.query.id]}</h1>

`


res.send(output)

})


위의 코드는 쿼리스트링으로 서로 다른 페이지를 나타낼 수 있게 하는 코드다.


사용자에게 url 로 id 값을 받아 (a코드 클릭을 통해 전송 or url 직접 입력) 

id 값에 따라 서로 다른 값을 출력하는 것이다.


이를 semantic URL로 바꿔보자 


기존에는 localhost:3000/topic?id=1 이라고 접속 했다면

이제 localhost:3000/topic/1 이라고 접속해보자


Cannot GET /topic/1


이라는 화면이 뜬다. 그럼 맨 끝에 1이 id값이라는 것을 알려주면 페이지를 표출할 수 있지 않을까??


기존의 코드에서 경로를 /topic/:id 로 바꾼다.

그러면 topic/ 다음에 나온 숫자가 id 값이라는 걸 컴퓨터가 인식할 수 있다. 


그리고 두번째로 기존의 쿼리스트링은 req.query.id를 썼다면,

semantic url은 params 로 바꿔야 인식 할 수 있다. 


코드의 변화는 다음과 같다. 


app.get('/topic:id',function(req,res){

var topics = [

'javascript is',

'nodejs is',

'express is'

]


var output = `

   <a href="/topic?id=0">Javascript</a>

        <a href="/topic?id=1">Nodejs</a>

        <a href="/topic?id=2">Express</a>

        <h1>${topics[req.params.id]}</h1>

`


res.send(output)

})


그림 localhost:3000/1/edit 라고 2개의 쿼리스트링이 올 때는 어떻게 해야할까?


app.get('/semantic/:id/:mode',function(req,res){

res.send(req.params.id+','+req.params.mode)

})


이런 코드를 입력하고


localhost:3000/semantic/1/edit 라는 url로 저속하면 브라우저는


1,edit 라는 값을 표출한다.