TIL035_210510
🍊 감상
📙 열품타 코딩 시간 6hour
👍🏼 -
👎🏼 -
🚀 목표
Udemy : The web developer bootcamp 2021 강좌 수강 (501/682)
개인 프로젝트 진행
Udemy : Javascript algorithms and data structures 강좌 수강 (11/249)
📣 The Web Developer Bootcamp 2021
40. Middleware: The Key To Express
417. More Middleware Practice
//Create middleware function
app.use((req, res, next) => {
console.log(req.method.toUpperCase());
next();
}); //GET
app.use((req, res, next) => {
console.log(req.method.toUpperCase(), req.path);
next();
}); //GET /dogs
app.use((req, res, next) => {
req.method = 'GET';
console.log(req.method, req.path);
next();
}); //make every request to get request
app.use((req, res, next) => {
req.requestTime = Date.now();
console.log(req.method, req.path);
next();
}); //GET /dogs
Setting Up A 404 Route
//Create middleware function
app.use((req, res, next) => {
console.log(req.method.toUpperCase());
next();
}); //GET
app.use((req, res, next) => {
console.log(req.method.toUpperCase(), req.path);
next();
}); //GET /dogs
app.use((req, res, next) => {
req.method = 'GET';
console.log(req.method, req.path);
next();
}); //make every request to get request
app.use((req, res, next) => {
req.requestTime = Date.now();
console.log(req.method, req.path);
next();
}); //GET /dogs
app.use((req, res) => {
res.statuse(404).send('NOT FOUND');
});
//마지막에 넣어야 그전 route 중 매칭되는 것 없을 때 실행됨
//match any request
419. Password Middleware Demo (not real auth)
app.use((req, res, next) => {
const { password } = req.query;
if (password === 'chckennugget') {
next();
}
res.send('sorry you need a password');
});
420. Protecting Specific Routes
const verifyPassword = (req, res, next) => {
const { password } = req.query;
if (password === 'chckennugget') {
next();
}
res.send('sorry you need a password');
};
app.get('/secret', verifyPassword, (req, res) => {
res.send('My secret is');
});
421. A New EJS Tool For Routes
npm i ejs-mate
const ejsMate = require('ejs-mate');
app.engine('ejs', ejsMate);
-> define layout file
new directory -> layouts
new file(in layouts) -> boilerplate.ejs
index.ejs 에서 body 부분만 남기고 맨 앞줄에
<%layout('layouts/boilerplate')%>
boilerplate.ejs에서는 원하는 줄에 <%- body %>
이런식으로 원하는 레이아웃 만들 수 있음, navbar 삽입하거나
422-429. Bootstrap5! Boilerplate
42. Handling Errors In Express Apps
431. Express' Built-In Error Handler
throw new Error('Password required')
432. Defining Custom Error Handlers
Error handling middleware functino
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('something broke')
})
//we have four parameters
//no loger get that default error handling
next(err)
builtin express error handling
아무것도 pass in 되지 않으면 next middleware 호출
error pass in 해야 error handler 역할
433. Our Custom Error Class
Make AppError.js
//in AppError.js
class AppError extends Error {
constructor(message, status) {
super();
this.message = message;
this.status = status;
}
}
module.exports = AppError;
//in another js file
throw new AppError('password required', 401);
Express is looking for a particular property on the error object called status or status code.
-> Just by making AppError class that has a status in it, It's all set up automatically
-> err.header도 마찬가지
app.use((err, req, res, next) => {
const { status = 500, message = 'Something went wrong' } = err;
res.status(status).send(message);
});
434. Handling Async Errors
app.get('/products/:id', async (req, res, next) => {
const { id } = req.params;
const product = await Product.findById(id);
if (!product) {
// throw new AppError('Product not found', 401);
// async 내에서 쓸 때는 next를 반드시 써줘야 한다
// next 앞에 return 써줘야 함
return next(new AppError('Product not found', 401));
}
res.render('products/show', { product });
});
435. Handling More Async Errors
app.put('/products/:id', async (req, res, next) => {
try {
const { id } = req.params;
const product = await Product.findByIdAndUpdate(id, req.body);
res.redirect(`/products/${product._id}`);
} catch (e) {
next(e);
//catch the error and pass it to next
}
});
436. Defining An Async Utility
Author And Source
이 문제에 관하여(TIL035_210510), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@keepcalm/TIL035210510저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)