ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Node.js] URL parsing | TypeError: handle[pathname] is not a function | favicon.ico에러
    JavaScript 2023. 12. 17. 10:40
    반응형

    ⚠️ TypeError: handle[pathname] is not a function

     

    <자세한 코드는 아래 깃허브 참고>

    https://github.com/heeheehoho/DevCourse/tree/main/backend/URLWeberver

    TypeError: handle[pathname] is not a function at route (/Users/jungheeho/Desktop/programmers/DevCourse/backend/URLWeberver/router.js:4:21) at Server.onRequest (/Users/jungheeho/Desktop/programmers/DevCourse/backend/URLWeberver/server.js:7:9) at Server.emit (node:events:513:28) at parserOnIncoming (node:_http_server:1072:12) at HTTPParser.parserOnHeadersComplete (node:_http_common:119:17) Node.js v18.15.0

     

    ❗️원인 분석

    router.js에서 handle[pathname]();를 호출할 때, handle 객체에 pathname에 해당하는 키가 존재하지 않을 경우를 처리하고 있지 않다. 이는 존재하지 않는 경로에 대한 요청이 들어왔을 때 TypeError를 발생시키는 원인!

    favicon.ico의 경우, 브라우저가 자동으로 요청하는 리소스이며, 이에 대한 처리가 requestHandler.js에 정의되어 있지 않고, 따라서 /favicon.ico 경로에 대한 요청이 들어올 때 handle['/favicon.ico']는 undefined이며, 이를 함수처럼 호출하려고 하면 오류가 발생한다.

     

    💡문제 해결 방법

    1. router.js 수정

    function route(pathname, handle) {
        console.log('pathname : ' + pathname);
        if (typeof handle[pathname] === 'function') {
            handle[pathname]();
        } else {
            console.log("No request handler found for " + pathname);
            // 기본 동작 추가, 예: 404 Not Found 응답 등
        }
    }
    exports.route = route;

     

    2. server.js 수정

    server.js에서 response를 보내는 부분을 router.js의 결과에 따라 조정(route 함수가 처리 결과를 반환하게 하여 그에 따라 다른 응답을 보낼 수 있음)

    function start(route, handle){
        function onRequest(request, response){
            let pathname = url.parse(request.url).pathname;
            console.log("Request for " + pathname + " received.");
    
            let result = route(pathname, handle);
            if (result) {
                response.writeHead(200, {'Content-Type' : 'text/html'});
                response.write(result);
            } else {
                response.writeHead(404, {'Content-Type' : 'text/html'});
                response.write("404 Not Found");
            }
            response.end();
        }
        http.createServer(onRequest).listen(8888);
        console.log("Server has started.");
    }
    
    exports.start = start;

    3. requestHandler.js에 기본 핸들러 추가

    기본 핸들러 함수를 추가하여 알 수 없는 경로에 대한 기본 동작을 정의할 수 있습니다.

    function notFound() {
        console.log('404 Not Found');
        return "404 Not Found";
    }
    
    let handle = {};
    handle['/'] = main;
    handle['/login'] = login;
    handle['/notfound'] = notFound; // 기본 핸들러 추가
    
    exports.handle = handle;

     

    반응형
Designed by Tistory.