프로그래밍/NodeJS

[NodeJS] Sematic URL여러개를 하나의 변수로 받아오기

Beginner:) 2023. 3. 2.
320x100

시맨틱(Semantic) URL을 사용할 떄 req.rarams를 이용해 쿼리의 값을 받아올 수 있다.

 

example) 

router.get('/download/:path', async function (req, res) {
	console.log(req.params.path);
});

라고 할 때, path의 값을 받아올 수 있다.

 

나의 경우 ftp 파일의 경로를 path로 받는데

 

/home/user/www/public/에 있는 test.txt를 받는다고 가정하자

 

그러면 /download/home/user/www/public/test.txt 라고 URL을 입력할텐데

 

위와 같이 사용하면 Error를 출력한다.

 

구분자 '/'를 따라 params를 나눠 받기 때문인데,

 

/home/user/www/public/test.txt 자체를 하나의 변수 req.params.path로 받기 위해서는 아래와 같이 사용하면 된다.

 

router.get('/download/:path(*)', async function (req, res) {
	console.log(req.params.path);
});

 

정규표현식을 사용하여 "/"구분자를 무시하고 

 

하나의 변수로 모두 받아올 수 있다.

 

router.get('/download/:path(*)', async function (req, res) {
	console.log("path : ", req.params.path);
});

 

IP/download/my_disk/test/test.txt를 get으로 입력했을 때

구분자 "/"를 무시하고 하나의 변수로 받아올 수 있는 것을 볼 수 있다.

 

반응형

'프로그래밍 > NodeJS' 카테고리의 다른 글

npm nodemodules import하기  (0) 2023.01.30
[JS] webserver 최대 크기 문제 해결(feat. dropzone)  (2) 2022.12.18
nodejs&nginx 연동하기  (0) 2022.12.04
[NodeJS] Buffer 함수 사용법  (0) 2021.01.26

댓글