• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    해결됨

matchedUrl 이 ReferenceError가 나면서 종료될 때

19.08.22 10:51 작성 조회수 94

0

강의 잘 듣고 있습니다.

강의대로 라우팅하고 실행해보고 싶어, 서버를 동작시켰는데 matchedUrl 이 ReferenceError 가 나면서 서버가 종료됩니다.

 

강의대로라면 기본값 연산자로 인해 로직이router[req.method.toLowercase()]['*'] 로 넘어가야 할 것 같은데, 넘어가지 않고 종료됩니다 ㅠㅠ

 

아래와 같은 에러가 나옵니다 : 

  (matchedUrl || router[req.method.toLowerCase()]['*'])(req, res);

     ^

ReferenceError: matchedUrl is not defined

 

 

답변 4

·

답변을 작성해보세요.

1

코드에 문제가 보이지 않습니다. 아직도 같은 에러가 나나요? 일단 서버를 껐다가 켜보세요. 혹시나 해서, 뒤에 세미콜론도 붙여보세요.

const matchedUrl = router[req.method.toLowerCase()][req.url];

0

와...해결됐습니다! 세미콜론 붙이는 습관을 들여야겠네요 ㅠㅠ 감사합니다!

0

빠른 답변 감사드립니다!! 집에 이제 와서야 봤습니다.

이미 위에 쓰긴 했습니다..

방금도 다시 한번 해봤는데 안되네요 ㅠㅠ

실행 코드 한 번만 봐주시면 감사하겠습니다. 

모듈 부분 제외하고, 일단 다 복붙 해놓긴 했습니다.

제가 뭔가 따라쓰다가 놓친건지...ㅠㅠ

console.log(mathedUrl)  결과값 :

[Function: /]

//리팩토링 시켜보자. express 가 아닌 순수 node 로 짜야할 때.
const router = {
get : {
'/' : (req, res) => {
fs.readFile('./restFront.html' , (err, data) => {
if (err) {
throw err
}
res.end(data);
});
},
'/users' : (req, res) => {
res.end(JSON.stringify(users));
},

// wild Card!! 이외의 모든 케이스.
'*' : (req, res) => {
fs.readFile(`.${req.url}`, (err, data) => {
return res.end(data)
});
},
},
post : {
'/users' : (req, res) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
})
req.on('end', () => {
console.log('Post 본문(body)', body);
const { name } = JSON.parse(body);
const id = +new Date();
users[id] = name
res.writeHead(201, {'Content-Type' : 'text/html; charset=utf-8'}); //이렇게 해야 한글이 안깨짐.
res.end('사용자 등록 성공')
});
}
},
patch : {

},
delete : {
'/users' : (req, res) => {
const key = req.url.split('/')[2];
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
return req.on('end', () => {
console.log('delete', body);
delete users[key]
return res.end(JSON.stringify(users))
});
},
},
put : {
'/users' : (req, res) => {
const key = req.url.split('/')[2];
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
return req.on('end', () => {
console.log('put', body);
users[key] = JSON.parse(body).name;
return res.end(JSON.stringify(users))
})
},
}
}
http.createServer((req, res) => {
// 우리가 만든 라우터 객체를 이용해보자.
//
const matchedUrl = router[req.method.toLowerCase()][req.url]
console.log(matchedUrl)
(matchedUrl || router[req.method.toLowerCase()]['*'])(req, res);

 
}).listen(5129, () => {
console.log('5129 번 포트에서 서버 대기 중')
})

0

한 줄 빼먹으신것 같습니다.

바로 위에 const matchedUrl = router[req.method.toLowerCase()][req.url];

넣어주세요.