1. Express
ํค์๋
Express ๋
URL ๊ตฌ์กฐ
REST API
HTTP Method(CRUD)
Express
Node.js ์น ์ ํ๋ฆฌ์ผ์ด์ ํ๋ ์์ํฌ
Node.js
V8์์ง์ผ๋ก ๋น๋๋ ์๋ฐ์คํฌ๋ฆฝํธ ๋ฐํ์
๋ฐํ์ : ํน์ ์ธ์ด๋ก ๋ง๋ ํ๋ก๊ทธ๋จ์ ์คํํ ์ ์๋ ํ๊ฒฝ
๋ค์ํ ์๋ฐ์คํฌ๋ฆฝํธ ์ ํ๋ฆฌ์ผ์ด์ ์ ์คํํ ์ ์๊ฒ ํด์ค(์ฃผ๋ก ์๋ฒ๋ฅผ ์คํ)
Express
Node.js์์ ํจ์จ์ ์ผ๋ก ์น ์ ํ๋ฆฌ์ผ์ด์ ์ ๊ฐ๋ฐํ ์ ์๋๋ก ๋์์ฃผ๋ ํ๋ ์์ํฌ
HTTP ์ ํธ๋ฆฌํฐ ๋ฉ์๋ ๋ฐ ๋ฏธ๋ค์จ์ด๋ก ์ฝ๊ณ ๋น ๋ฅด๊ฒ API๋ฅผ ์์ฑํ ์ ์์
ts-node
.ts ํ์ผ์ ๋ฐ๋ก ์ปดํ์ผํ์ง ์๊ณ node.js์์ ํ์ ์คํฌ๋ฆฝํธ๋ฅผ ์คํํ๋ ๋๊ตฌ
Express ํ๊ฒฝ ์ค์
mkdir express-demo-app
cd mkdir express-demo-app
.gitignore ์ธํ
touch .gitignore
echo "/node_modules/" > .gitignore
ํจํค์ง ์ด๊ธฐํ
npm init -y
TypeScript
npm i -D typescript
npx tsc --init
ESLint
npm i -D eslint
npx eslint --init
ts-node
npm init -y
Express ์ค์น
npm i express
npm i -D @types/express
Hello World ์์
app.ts http://localhost:3000/
์ผ๋ก GET์์ฒญ์ด ๋ค์ด์ค๋ฉด Hello, world!
๋ฅผ ์๋ต
import express from 'express';
const port = 3000;
const app = express();
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
ts-node๋ก ์คํ
npx ts-node app.ts
์ฝ๋ ์์ ์ ์๋์ผ๋ก ๋ฐ์๋๋๋ก nodemon ์ฌ์ฉ
npm i -D nodemon
npx nodemon app.ts
package.json script ์ธํ
"scripts": {
"start": "npx nodemon app.ts",
"lint": "eslint --fix ."
},
REST API
URI๋ ์ ๋ณด์ ์์์ ํํ
/write-post
์ฒ๋ผ ๋์์ ํํํ์ง ์๊ณ/post
์ฒ๋ผ ์์๋ง ๋ช ์
์์์ ๋ํ ํ์๋ HTTP Method๋ก ํํ(GET, POST, PUT, DELETE)
Collection(๋ณต์)๊ณผ Item(Element)(๋จ์)๋ก ๋๋จ
Read (Collection) โ GET /products โ ์ํ ๋ชฉ๋ก ํ์ธ
Read (Item) โ GET /products/{id} โ ํน์ ์ํ ์ ๋ณด ํ์ธ
Create (Collection Pattern ํ์ฉ) โ POST /products โ ์ํ ์ถ๊ฐ (JSON ์ ๋ณด ํจ๊ป ์ ๋ฌ)
Update (Item) โ PUT ๋๋ PATCH /products/{id} โ ํน์ ์ํ ์ ๋ณด ๋ณ๊ฒฝ (JSON ์ ๋ณด ํจ๊ป ์ ๋ฌ)
Delete (Item) โ DELETE /products/{id} โ ํน์ ์ํ ์ญ์
Thinking in React ์์
app.get('/products', (req, res) => {
const products = [
{
category: 'Fruits', price: '$1', stocked: true, name: 'Apple',
},
{
category: 'Fruits', price: '$1', stocked: true, name: 'Dragonfruit',
},
{
category: 'Fruits', price: '$2', stocked: false, name: 'Passionfruit',
},
{
category: 'Vegetables', price: '$2', stocked: true, name: 'Spinach',
},
{
category: 'Vegetables', price: '$4', stocked: false, name: 'Pumpkin',
},
{
category: 'Vegetables', price: '$1', stocked: true, name: 'Peas',
},
];
res.send({ products });
});
http://localhost:3000/products
์ ์ํ์ฌ ํ์ธ
CommandLine์ผ๋ก ํ์ธ
curl localhost:3000/products
http localhost:3000/products
Last updated