
1. node.ts 환경 세팅
git init
touch .gitignore
node_modules
dist
npm init -y //package.json 파일 생성
npm i //package-lock.json 파일 생성
npm i -D typescript ts-node @types/node //node_modules 폴더 생성
npx tsc --init //tsconfig.json
npm i -D concurrently //dist 폴더
npm install express
npm install -D @types/express
npm install body-parser //bodyparser 설치
npm i jsonwebtoken
// tsconfig.json
"dev": "concurrently 'tsc --watch --project tsconfig.json' 'node --watch dist/app.js'",
"build": "tsc --project tsconfig.json",
"start": "node dist/app.js"
//추가 팁
,"prestart": "npm run dev"
import express from "express";
const app = express();
const port = 5555;
app.listen(port, () => {
console.log("서버 작동중");
});
2. 서버 만들기
import express from 'express';
const app = express();
const port = 5555;
npm install body-parser
app.use(bodyParser.json());
//전체코드
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
const port = 5555;
app.use(bodyParser.json());
app.get("/", (req, res) => {
res.send("HelloWorld")
});
(1) posts.json 파일 만들기
src/data 폴더에 posts.json 파일 생성 후 붙여넣기
(2) 서버로 불러오기
기본 구조 : express명.요청("경로", (요청, 응답) => {내용})
전체 포스트 불러오기
app.get("/posts", (req, res) => {
const postId = req.query.postId;
if (postId) {
const post = posts.find((post) => post.id === Number(postId));
res.json(post);
} else {
res.json(posts);
}
res.json(posts)
});
app.get("/posts/:postId", (req, res) => {
const postId = req.params.postId;
const post = posts.find((post) => post.id === Number(postId));
})
app.get(/.*fly$/, (req, res) => {
res.send('/.*fly$/')
})
정규표현식도 사용가능