어플리케이션 미들웨어
라우터 미들웨어
index.js
const express = require('express');
const usersRouter = require('./routes/users');
const adminRouter = require('./routes/admin');
const setUser = require('./middlewares/set-user');
const adjuerQuery = require('./middlewares/adjust-query');
const app = express();
app.use(adjuerQuery);
app.get('/', (req, res) => {
res.send("OK");
});
app.use('/users', setUser(), usersRouter);
app.use('/admin', setUser("admin"), adminRouter);
app.listen(8080);
set-user.js
const users = require('../data/users');
const admins = require('../data/admins');
const setUser = (type) => (req, res, next) => {
const { userName } = req.query;
if (type === "admin") {
req.user = admins[userName];
} else {
req.user = users[userName];
}
next();
}
module.exports = setUser;
요청과 응답
GET /users?userName=alice
"USER: alice, 1"
GET /users?userName =alex
"USER: NotFound, 0"
const express = require('express');
const app = express();
const hasError = (req, res, next) => {
next("ERROR");
}
app.get('/', (req, res) => {
res.send("OK");
});
app.get('/success', (req, res) => {
res.send("SUCCESS");
});
app.get('/fail', hasError, (err, req, res, next) => {
res.send(`Request failed with ${err}`);
});
// 오류처리 미들웨어 추가하기
app.listen(8080);
next() 괄호안에다가 뭘 넣으면 error처리 미들웨어의 첫번째 인자로 간다.
exports.authorList = () => {
const authors = notes.map(({ author }) => author);
return [...new Set(authors)];
}
new Set(배열) 하면 {} 형태로 나와서 spread operator로 다꺼낸담에 []안에 다시넣어줘야한다.