Node.js+express로 백엔드 서버 만들기

Gisele·2021년 1월 18일
0

Node.js

Node.js®는 Chrome V8 JavaScript 엔진으로 빌드된 JavaScript 런타임입니다.

  • node.js에서 제공하는 http 모듈을 이용해 서버를 만듦

Express

  • Node.js를 위한 빠르고 개방적인 간결한 웹 프레임워크
  • 자유롭게 활용할 수 있는 수많은 HTTP 유틸리티 메소드 및 미들웨어를 통해 쉽고 빠르게 강력한 API를 작성할 수 있다
$ npm i express
var express = require('express')
var app = express()

라우팅

  • 라우팅은 URI(또는 경로) 및 특정한 HTTP 요청 메소드(GET, POST 등)인 특정 엔드포인트에 대한 클라이언트 요청에 애플리케이션이 응답하는 방법을 결정하는 것

  • 각 라우트는 하나 이상의 핸들러 함수를 가질 수 있으며, 이러한 함수는 라우트가 일치할 때 실행됨

      app.get('/', function (req, res) {
        res.send('Hello World!');
      });
    

주요 API

api기능
app.get(path,callback[,callback])해당 path의 get 요청(가져오기) 을 받아 callback 함수로 처리
app.post(path, callback [, callback ...])해당 path의 post 요청(생성) 을 받아 callback 함수로 처리
app.put(path, callback [, callback ...])해당 path의 put 요청(수정) 을 받아 callback 함수로 처리
app.delete(path, callback [, callback ...])해당 path의 delete 요청(삭제) 을 받아 callback 함수로 처리
res.send([body])http response를 전송,
body parameter로 Buffer object,String, object, Boolean,Array 가능
res.status(status code)응답으로 http status code를 전송
res.json({key:value})응답을 json 형식으로 전송

Backend server 만들기

express 설치, 기본 골격

$ npm i express

//app.js
const http = require('http');

const app = express()

app.get('/',(req,res)=>{
    res.send('hello express');
})

app.get('/api/user',(req,res)=>{
    res.json('hi,user')
})

app.listen(3065,()=>{
    console.log('서버 실행 중')
});

api router 분리

  1. api 별로 파일 분리

  2. 각 모듈에 router 설정, exports

const router = exporess.Router()
router.get(path,callbackFunction)
// post.js
const express = require('express');

const router = express.Router()

router.get('/',(req,res)=>{
    res.json([
        {id:1,content:'hello'},
        {id:2,content:'hello2'},
        {id:3,content:'hello3'},
    ])
})

router.post('/',(req,res)=>{
    res.json({
        id:1,
        content:'랄랄라'
    })
})

router.delete('/api/post',(req,res)=>{

})


module.exports = router;
  1. 라우터 사용
    app.use(path, router)

📑 reference

profile
한약은 거들뿐

0개의 댓글