[nodeJS] express basic routing

jungmin kim·2022년 2월 23일
0

NodeJS

목록 보기
4/6

express 설치 명령어

npm i express

express 서버 구현 기본 원리

  • node가 아닌 express로 서버를 구현하는 이유는 좀 더 구조적으로 라우팅을 짤 수 있다.

method

  • app.get : 가져오다
  • app.post : 생성하다 (로그인 등 애매한 경우 post 추천)
  • app.put: 전체 수정
  • app.delete: 제거
  • app.patch: 부분 수정 (수정작업은 대부분 patch로 활용하게 됨)
  • app.options: 찔러보기
  • app.head: 헤더만 불러옴, 거의 안씀.
const express = require('express');
const app = express();
// 루트 url 불러오기
app.get('/', (req, res) => {
  res.send('hello express');
});
// /api url 불러오기
app.get('/api', (req, res) => {
  res.send('hello api');
});
//게시글 목록 조회 예시
app.get('/api/posts', (req, res) => {
  res.json([
    { id: 1, content: 'hello'},
    { id: 2, content: 'hello2'},
    { id: 3, content: 'hello3'},
  ]);
});
// 게시글 생성 예시
app.post('/api/post', (req, res) => {
  res.json({ id: 1, content: 'hello'});
});
//게시글 제거 예시
app.delete('/api/post', (req, res) => {
  res.json({ id: 1 });
});
//서버 실행
app.listen(3065, () => {
  console.log('서버 실행 중');
});
  • GET method는 브라우저에서 불러오기 가능

  • POST method는 안됨.

  • POST는 postman 프로그램에서 확인 가능

  • 백앤드 개발자의 역할: api routing을 하는 역할

router 분리

/post/... 이 url처럼 자주 쓰이는 라우터가 있는 경우, 분리가 가능하다.

post.js

const express = require('express');
const router = express.Router();
router.post('/', (req, res) => { // POST /post
  res.json({ id: 1, content: 'hello'});
});

router.delete('/', (req, res) => { // DELETE /post
  res.json({ id: 1 });
});
module.exports = router;
  • node에서는 import/ export default 코드 대신, require, module.exports 코드로 쓰이고 있다.

app.js

//분리한 post.js import
const postRouter = require('./routes/post');
// /post url에 해당하는 라우터 
app.use('/post', postRouter);

0개의 댓글