Node.js

[NodeJS] Express

min_s 2025. 2. 11. 10:32
npm install express@latest

다음 명령어를 입력한다. 현재 디렉터리에 node_modules와 package.json이 생길것이다.

 

const express = require('express');

const app = express();

app.get('/', (req, res) => {
    res.send('hello express');
});

app.listen(3000, () =>{
    console.log('익스프레스 서버 실행');
});

 

다음 코드를 입력하고 터미널에서 node app 을 입력하여 express 서버를 실행해보자.

이후 'localhost:3000'을 접속하면 서버가 정상적으로 작동하는것을 확인할 수 있다.

이제 nodemon을 활용해보자

포트를 3001로 지정해준후 npx nodemon app을 입력.

3000포트가 아직 살아있어서 3001로 설정했다.

const express = require('express');

const app = express();

app.set('port', process.env.PORT || 3001);
app.get('/', (req, res) => {
    res.send('hello express');
});

app.post('/', (req, res) => {
    res.send('hello express');
});

app.get('/about', (req, res) => {
    res.send('hello express');
}); 

app.listen(app.get('port'), () =>{
    console.log('익스프레스 서버 실행');
});

다음과 같은 에러를 입력해도 익스프레스 서버에서 자동으로 404 에러 처리를 해준다.

ex)localhost:3001/abouttttt
자세한 내용은 개발자도구에서 확인할 수 있다.

node.js만으로 구현했을 때와 달리, 많은 if문을 사용하지 않아도 된다.
nodemon은 수정사항이 있을 때 자동으로 서버를 재시작해준다.

 

더 자세히 서버를 실행해보기 위해 index.html 파일을 하나 생성했다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>익스프레스 서버</title>
</head>
<body>
    <h1>익스프레스</h1>
    <p>공부중</p>
</body>
</html>

app.js 코드를 다음과 같이 수정한다.

const express = require('express');
const path = require('path');

const app = express();

app.set('port', process.env.PORT || 3001);
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
});

app.post('/', (req, res) => {
    res.send('hello express');
});

app.get('/about', (req, res) => {
    res.send('hello express');
}); 

app.listen(app.get('port'), () =>{
    console.log('익스프레스 서버 실행');
});

이후 재시작된 서버에 다시 접속하면

 


코드에 중복을 제거하기 위해 미들웨어를 사용해보자.

app.use((req, res, next) => {
    console.log('모든 요청에 실행하고 싶어요')
    next();
})

next를 실행해줘야만 다음 단계로 넘어간다. 주의하자.

또 이제 프로젝트의 규모가 커져 라우터들이 많이 요구된다면, 모든 경로를 작성하기는 부담스럽다.

그럴 경우엔 다음과 같이 와일드카드를 이용할 수 있다.

app.get('/category/:name', (req,res) =>{
res.send(`hello ${req.params.name}`);
});

와일드 카드는 다른 라우터들 아래에 위치해야한다. 코드는 위에서부터 순차적으로 실행되기 때문이다.