Study/Node.js
express 시작__미들웨어 app.use()
Minhhk
2023. 10. 5. 23:05
npm init
npm i express
npm -D nodemon -> package.json 에 script 부분에
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon app"
},
지정한 뒤,
app.js 파일을 npm start로 실행
app.use에 매개변수가 req, res, next인 파라미터를 넣는다.
미들웨어는 위에서부터 아래로 순서대로 실행 -> 요청과 응답 사이에 특별한 기능을 추가 가능!
이번에는 next 파라미터는 다음 미들웨어로 넘어가는 함수이며,
next() 실행 시키지 않으면 다음 미들웨어 실행이 안됨..
const express = require("express");
const path = require("path");
const app = express();
app.set("port", process.env.PORT || 3000);
// 미들웨어 사용 app.use()
app.use(
(req, res, next) => {
console.log("middleWare Using...");
next(); // next() 실행 해줘야 다음 라우터로 이동한다!
},
// 이런 방식으로 에러 처리?
(req, res, next) => {
try {
console.log("error accured");
} catch (error) {
// next에 에러를 넣어 하단 에러 미들웨어로 보내버림
next(error);
}
}
//! 이렇게 미들웨어 에러 처리는 잘 안씀.
// ,
// (req, res, next) => {
// throw new Error("에러 발생");
// }
);
// html 응답 -> res.sendFile()
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "./index.html"));
});
// /about 에서만 실행!
app.use("/about", (req, res, next) => {
console.log("middleWare about...");
next(); //
});
app.get("/hello", (req, res) => {
res.send("hello express go");
});
// /hello/:name => /hello/lee , /hello/kim 다 아래 라우터 출력
app.get("/hello/:name", (req, res) => {
res.send("라우터 파라미터(와일드 카드),,출력");
});
app.get("/json", (req, res) => {
res.json({ hello: "kim" });
});
// 모든 get 요청에 아래 라우터 출력
// app.get("*", (req, res) => {
// res.send("모든 get 요청에 다음을 실행~");
// });
//! 404 처리는 에러처리 위에, 라우터 아래에
app.use((req, res, next) => {
res.send("404 에러");
// 같은 맥락_ 단지 상태 지정을 할 수 있다.
// res.status(404).send("404 에러");
});
//! 에러 처리는 마지막에!, 꼭 4개 매개변수
app.use((err, req, res, next) => {
console.error(err);
res.send("에러발생!!!!");
});
app.listen(app.get("port"), () => {
console.log("3000포트 서버 실행중");
});
한 라우터 안에
res.send()
res.sendFile()
동시에 절 때!! 쓰지 않기!
->
cannot set headers after they are sent to the client 에러 발생