Node.js

[Node.js] express 입문

KrystalJo 2022. 9. 18. 14:15

1. express 프로젝트 초기 생성 및 설치

npm init

 (1) 이 명령을 실행하면 몇 가지 질문이 이어지고, 답한 내용에 따라 package.js 파일이 만들어짐

=> entry point를 묻는 질문에는 meadowlark.js라고 답함

 

npm install express@4

(2) npm install express04를 실행하면 node_modules 디렉터리가 설치되고, package.json 파일이 업데이트가 됨

=> node_modules 디렉터리는 언제는 npm으로 다시 생성할 수 있음 따라서 깃 저장소에 추가할 필요가 없음

(npm install 할 때마다 업데이트가 됨)

 

#npm 설치 패키지 깃 무관
node_modules

#.DS.Store(OXS) 처럼 운영체제에서 만든느 파일, 백업 파일 등
# 무시할 파일을 추가

(3) .gitignore 파일 생성 후 위의 코드 추가

=> node_modules git commit하지 않도록 추가

 

// 원래는 기본적으로 app.js, server.js 이름으로 저장을 함 
// node가 실행될 때 가장먼저 실행되는 파일

const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

app.use((req, res) => {
    res.type('text/plain');
    res.status(404);
    res.send('404 - Not Found');
})

app.use((req, res) => {
    res.type('text/plain');
    res.status(500);
    res.send('500 - Server Error');
})

app.listen(port, () => console.log(
    'Express started on http://localhost:${port};' +
    'press Ctrl + C to terminate'))

(4) express를 사용하여 3000 포트로 서비스를 기동할 수 있도록 코드를 추가 - 파일이름은 기본적으로 app.js, server.js 로 생성

 

app.get('/', (req, res) =>{
    res.type('text/plain')
    res.send('Meadowlark Travel')
})

app.get('/about', (req, res) =>{
    res.type('text/plain')
    res.send('About Meadowlark Travel')
})

//custom 404 page
app.use((req, res) => { //use는 미들웨어랑 관계 있는 메서드 
    res.type('text/plain');
    res.status(404);
    res.send('404 - Not Found');
})

(5) 페이지를 렌더링해줄 코드 추가 

 => app.METHOD(app.get / app.post)를 사용하여 라우팅을 해줌 

=> ** 위 메소드는 기본적으로 대소문자를 구분하지 않음 /about, /About, /about?foo=bar 모두 똑같이 동작함

 

 

** 익스프레스에서는 라우트와 미들웨어의 순서가 중요함

app.get('/about*', (req, res) =>{
    // 콘텐츠 정송
})

app.get('/about/contact', (req, res) =>{
    // 콘텐츠 정송
})

app.get('/about/directions', (req, res) =>{
    // 콘텐츠 정송
})

=> 맨위에 /about* 와일드카드가 존재하여 맨위의 경로로 라우팅이 되기 때문에 순서문제가 일어날 수 있어서 주의해서 사용해야 함

 

 

** 익스프레스에서는 라우트를 사용하는 이유는 편리함 때문

const server = http.createServer((req, res) => {
    // 쿼리스트링, 옵션인 마지막 슬래시를 없애고 소문자로 바꿔서 url을 정규화합니다.
    const path = req.url.replace(/\/?(?:\?.*)?$/, '').toLowerCase();
}

=> 익스프레스를 사용하지 않으면 위의 코드처럼 URL의 마지막 슬래시를 없애고 소문자로 만드는 코드를 추가해야함

=> 하지만 app.METHOD를 사용하면 이런 작업을 자동으로 대신함