Hello World Example
소개 코드
// app1.js
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`http://localhost:${port}에 연결 중 ...`);
});
- 서버를 3000번 포트에 연결(listen)하며, '/' 페이지에 'Hello World!'라는 글자가 나오게 응답(res) 요청한다.
- npm을 활용하여 express를 설치 필요
node 실행 결과
Basic routing
- 라우팅은 클라이언트의 요청에 어플리케이션이 HTTP 메서드에 따라 응답하는 방법을 결정하는 것을 말한다.
라우팅 기본구조
app.METHOD(PATH, HANDLER);
- 대표 METHOD 종류
- get : 읽기 요청(Read)
- post : 생성 요청(Create)
- put : 수정 요청(Update)
- delete : 삭제 요청(Delete)
- PATH : 서버 경로
- HANDLER : 라우트가 일치할 경우에 실행되는 함수
Static files
// middleware 선언
app.use('/static', express.static('public'));
// 정적 파일 불러오기
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/index.html
- Express에서 정적 파일(HTML, CSS, JS, 기타 미디어 파일 등)도 제공할 수 있다.
- Express에서 기본으로 제공하는 미들웨어 함수 'express.static'을 사용해야 한다.
- use 메서드 활용
app.use('/static', express.static(__dirname + '/public'));
- 위와 같이 상대경로보다는 절대경로를 사용하는 것이 더 안전하다.
※ 정리한 내용 외에 express 설치하는 방법, 생성기 사용 방법 등의 내용을 확인할 수 있다.
참고
'기타' 카테고리의 다른 글
[regexp] 정규표현식 정리 (0) | 2021.12.22 |
---|---|
[Linux] 리눅스 간단 정리(환경 구성, 관련 명령어) (0) | 2021.12.04 |
[Git] Git 처음 시작과 상태 (0) | 2021.09.14 |