티스토리 뷰
OK 반환 서버
- 모든 요청에 "OK"를 반환하는 서버는 다음과 같다.
const http = require('http');
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end('OK');
});
server.listen('3000', () => console.log('OK 서버 시작!'));
res.setHeader('Content-Type', 'text/html');
- 응답의 헤더 값을 설정한다.
- 'text/html'은 텍스트를 html로 해석하겠다는 의미다.
res.end('OK');
- "OK"를 전달하고 응답을 종료한다.
server.listen(port, callback());
- createServer()로 서버 인스턴스를 생성하고, listen() 함수로 서버를 실행한다.
서버 실행
- 터미널에서 다음과 같이 실행하면 서버를 시작할 수 있다.
$ node [생성한 파일명] |
- 서버를 시작하면 콘솔에는 다음과 같이 출력되며, 브라우저에서 localhot:3000 을 입력하여 접속 시 다음과 같은 문자가 나타난다.
터미널에서![]() |
브라우저에서![]() |
라우터
- 일반적인 웹 서버는 URL 경로에 따라 다른 응답을 준다. 이러한 기능을 라우터라고 한다.
const http = require('http');
const url = require('url');
http.createServer((req, res) => {
const path = url.parse(req.url, true).pathname;
res.setHeader('Content-Type', 'text/html; charset=utf-8');
if(path === "/user"){
res.end("[user] name : ysh, age: 30");
}else if(path === "/feed"){
res.end(`<ul>
<li>picture1</li>
<li>picture2</li>
<li>picture3</li>
</ul>`);
}else{
res.statusCode = 404;
res.end("404 page not found");
}
}).listen('3000', () => console.log('Router Server.'));
const path = url.parse(req.url, true).pathname;
- url 모듈을 사용해 요청(req)으로 받은 url의 pathname을 얻는다.
- url이 "localhost:3000/user" 라면 pathname은 "/user"가 된다.
- parse 함수의 두 번째 인수인 true는 쿼리 스트링도 함께 파싱할지 여부를 설정한다. 경로 다음의 ? 기호 뒤 키=값 형태로 붙인다.
if(path === "/user")
- /user로 요청이 온 경우 res.end 안의 내용과 같이 응답한다.
확인
- 서버 실행 후 브라우저에서 "localhost:3000/user" 와 같이 입력하여 확인한다.
- "/user"가 아닌 다른 경로를 입력하면 "404 page not found" 가 나타날 것이다.
Express
- 위는 Nodejs의 기본 라이브러리를 이용하여 웹 서버를 만든 것이다. 위와 같이 서버 코드를 작성하는 것은 번거롭고 불편하다.
따라서 여러 기능을 제공하는 오픈 소스 중 익스프레스를 설치하여 작성한다.
Express 설치
- Express는 기본 라이브러리가 아니므로 설치해야 한다. Nodejs와 같이 설치되는 npm으로 설치하면 된다.
- 코드를 작성하는 디렉터리에서 터미널을 열고, 다음 명령어를 입력하여 express를 설치한다.
$ npm install express
Express Server
- Express 를 사용하는 서버 코드를 작성한다.
const express = require('express'); // express 모듈 불러오기
const app = express(); // express를 초기화 후 app에 할당
const port = 3000;
app.get('/', (req, res) => { // / 으로 요청이 오는 경우 실행됨
res.set({'Content-Type': 'text/html; charset=utf-8'}); // 헤더값 설정
res.end('Hello, Express!');
});
app.listen(port, () => { // 서버를 기동해 클라이언트 요청을 기다림
console.log(`START SERVER : using port ${port}`);
});
const app = express();
- express()를 실행해 express 인스턴스를 만들고 app에 할당한다.
app.get('/', (req, res) => { ... }
- app.get 을 사용해 url의 path가 '/' 이면서 http 메서드가 get 인 경우 콜백 함수를 실행한다.
확인
- 서버 실행 후 브라우저로 접속해 보면 res.end() 안에 작성된 'Hello, Express!' 문구가 보일 것이다.
Express를 이용한 API 서버
- REST API를 따르는 API 서버를 만든다.
- 이 API 서버는 게시판에서 사용되는 기능을 가지며, API 항목은 다음과 같다.
경로 | HTTP 메서드 | 설명 |
/ | GET | 게시판 목록 |
/posts | POST | 게시판 글 작성 |
/post/:id | DELETE | 게시글 삭제 |
- 서버 코드
const express = require('express');
const app = express();
let posts = []; // 게시글 리스트로 사용할 posts에 빈 리스트 할당
// req.body를 사용하려면 JSON 미들웨어를 사용해야 한다.
// 사용하지 않으면 undefined로 반환
app.use(express.json()); // JSON 미들웨어 활성화
// POST 요청 시 컨텐트 타입이 application/x-www-form-urlencoded인 경우 파싱
app.use(express.urlencoded({ extended: true})); // JSON 미들웨어와 함꼐 사용
app.get('/', (req, res) => { // / 로 요청이 오면 실행
res.json(posts); // 게시글 리스트를 JSON 형식으로 보여 줌.
});
app.post('/posts', (req, res) => { // /posts 로 요청이 오면 실행
const { title, name, text } = req.body; // HTTP 요청의 body 데이터를 변수에 할당
// 게시글 리스트에 새로운 게시글 정보 추가
posts.push({id: posts.length + 1, title, name, text, createdDt: Date()});
res.json({title, name, text});
});
app.delete('/posts/:id', (req, res) => {
const id = req.params.id; // app.delete에 설정한 path 정보에서 id값을 가져옴.
const filteredPosts = posts.filter((post) => post.id !== +id); // 글 삭제 로직
const isLengthChanged = posts.length !== filteredPosts.length; // 삭제 확인
posts = filteredPosts;
if(isLengthChanged){ // posts의 데이터 개수가 변경되었으면 삭제 성공
res.json("OK");
return;
}
res.json("NOT CHANGED"); // 변경되지 않음
});
app.listen(3000, () => {
console.log('API Server Started!');
});
app.use(express.json());
- 미들웨어를 활성화한다. express.json() 미들웨어는 HTTP 요청의 body를 사용하도록 해 준다.
- 이 미들웨어를 사용하지 않으면 req.body 값이 undefined로 나타난다.
app.use(express.urlencoded( { extended: true} )
- 이 미들웨어는 컨텐트 타입이 application/x-www-form-urlencoded인 경우 파싱해 준다.
- POST 요청은 대부분 application/x-www-form-urlencoded 타입이라서 express.json()과 함께 사용한다.
- application/x-www-form-urlencoded 타입은 키=값&키2=값2 같은 키=값 조합 형태를 가진 데이터를 말한다.
app.get / app.post / app.delete
- 각 HTTP 메서드에 해당하는 부분이다.
API 테스트
- CURL 혹은 Postman 프로그램을 이용하여 API를 테스트할 수 있다.
# 게시물 조회
> curl -X GET http://localhost:3000
# 게시물 등록
> curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "title=제목&name=ysh&text=게시물1" http://localhost:3000/psots
# 게시물 삭제
>curl -X DELETE localhost:3000/posts/1
- 위와 같이 Express로 웹 및 API 서버를 만들 수 있다.
'Javascript > Node.js' 카테고리의 다른 글
Node.js 서버 (0) | 2024.04.17 |
---|---|
Node.js 란 (0) | 2024.04.17 |
- Total
- Today
- Yesterday
- 세션
- 미들웨어
- html css
- el
- script element
- Spring MVC
- HTML
- javaserverpage
- 내장객체
- react
- 네트워크
- 서블릿
- CSS 속성
- FMT
- Redux
- nodejs
- 제이쿼리
- Spring
- 스프링
- Binding
- httpServletRequest
- Network
- 리액트
- 서브넷팅
- CSS
- Session
- Java Server Page
- a 태그
- Servlet
- JSP
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |