본문 바로가기

TIL/Node.js, express

req.body에 한글이 넘어와서 TypeError 발생 (Request path contains unescaped characters)

문제 상황

유저가 입력한 url을 전달 받아 이를 크롤링하는 코드가 구동중이다.

 

그런데 Velog의 경우, 다음과 같이 url에 한글이 포함되는 경우가 있다.

“https://velog.io/@username/가나다라마바사”

 

request 값으로 한글을 전달받게 되면 다음과 같은 에러가 발생한다.

 

TypeError [ERR_UNESCAPED_CHARACTERS]: Request path contains unescaped characters

 

해결

자바스크립트 내장 함수인 encodeURI()를 쓰면 된다.

encodeURI(req.body.url)

하지만 전달받는 값이 한글이 아니라 영문일 경우, encodeURI로 감싸게 되면 원래의 문자열과 달라진다.

 

전달받는 값이 한글일때를 식별하여 encodeURI를 부분적으로 적용시킬 수는 없을까?

 

 

정규표현식을 사용하면 된다.

더보기

 

const korean = /[ㄱ-ㅎ|ㅏ-ㅣ|가-힣]/;

korean.test(string);

위와 같이 한글 포함 여부를 검사할 수 있다.

 

최종 코드는 다음과 같다.

 

// 최종 코드
...
const axiosOptions = {
  url: req.body.url,
  method: "GET",
};
const korean = /[ㄱ-ㅎ|ㅏ-ㅣ|가-힣]/;
if (korean.test(req.body.url)) {
  axiosOptions.url = encodeURI(req.body.url);
}
html = await axios(axiosOptions);
$ = cheerio.load(html.data);
crawledData = {
  image: $('head meta[property="og:image"]').attr("content"),
  desc: $('head meta[property="og:description"]').attr("content"),
  title: $('head meta[property="og:title"]').attr("content"),
};
...