
const express = require('express')
const app=express()
app.get('/',(req,res)=>res.send('Hello World!'))
app.listen(3000, ()=> console.log('Example app listening on port 3000'))
위에 const app=express() 부분을 보면, express를 함수처럼 호출하고있네? 그럼 리턴된 값을 app에 넣고있는거고.
리턴값으로는 Application이라는 객체를 리턴하는데, Application이라는 객체가 갖고있는 메소드들중 하나가 앞으로 자주 볼 get() 이라는 거임.
app.get(path, callback[,callback...])와 같이 사용된다.
const express = require('express');
const server = express();
server.get("/",(req,res)=>{
res.send("<h1>hello from nodejs</h1>");
});
server.listen(3000,(err)=>{
if(err) return console.log(err);
console.log("The server is listening on port 3000");
});
미들웨어는 요청과 응답 중간에 위치한다. 미들웨어는 함수이며 Express에서는 사실상 거의 모든 게 미들웨어이다. 요청과 응답을 조작하여 기능을 추가하거나 나쁜 요청을 거르기도 한다.
미들웨어는 순서가 있다. 상단에 있는 미들웨어가 먼저 실행되며 하단으로 갈수록 나중에 실행된다. next를 호출을 하느냐 마느냐에 따라 다음 미들웨어가 실행될 수도 있고 실해되지 않을 수도 있다.
app.use(미들웨어)app.use(미들웨어 사용경로, 미들웨어)app.METHOD(미들웨어)app.METHOD(미들웨어 사용경로, 미들웨어)❖ METHOD: get, post, put 등의 http 메서드
app.use((req, res, next) => {
console.log('미들웨어입니다.');
next();
});
미들웨어의 함수 영역
(req, res, next) => {
console.log('미들웨어입니다.');
next();
}
app.get('/', (req, res, next) => {
res.sendFile(path.join(__dirname, '/index.html'));
next();
}, (req, res) => {
throw new Error('에러 발생');
});
코드에서 미들웨어 함수 영역은 아래와 같다.
미들웨어 두 개가 연결되어 있는 형태이다.
(req, res, next) => {
res.sendFile(path.join(__dirname, '/index.html'));
next();
}, (req, res) => {
throw new Error('에러 발생');
}
app.use()는 모든 요청에 미들웨어를 실행하며, app.http메서드()는 각 요청에서 미들웨어가 실행된다.
예를 들어, app.get()은 GET 요청에서 미들웨어가 실행되며, app.post()는 POST 요청에서 미들웨어가 실행되는 것이다.
app.use(미들웨어)
모든 요청에서 미들웨어 실행app.use('/user', 미들웨어)
user로 시작하는 모든 요청에서 미들웨어 실행app.get('/user', 미들웨어)
user로 시작하는 GET 요청에서 미들웨어 실행
...
const requestHandler = (req, res) => {
if(req.url === '/lower') {
if (req.method === 'GET') {
res.end(data)
} else if (req.method === 'POST') {
req.on('data', (req, res) => {
// do something ...
})
}
}
}
const router = express.Router()
router.get('/lower', (req, res) => {
res.send(data);
})
router.post('/lower', (req, res) => {
// do something
})

postman 만들어놓고 테스트 진행하는게 좋음