[nodejs] 간단한 restfulAPI 서버만들기
본문 바로가기

Backend/node.js

[nodejs] 간단한 restfulAPI 서버만들기

- nodejs 프레임워크중 하나인 express를 쓰지않고 간단한 restfulAPI만으로 crud를 구현해보자

- 편리를 위해 typescript와 서버를 자동으로 껏다켜주는 nodemon과 httpie는 병행함

 

서버만들기 기초

http모듈은 Node.js에서 제공해주는 모듈중 하나로 require메소드를 통해 HTTP서버(웹서버)를 만든다.

클라이언트가 웹브라우저를통해 서버에 연결, 데이터을 요청하면 웹서버는 서비스를 준비, 데이터를 전송할수있도록 도와준다.

 

* HTTP란 Hyper Text Transfer Protocol의 약자로 인터넷에서 데이터를 주고받는 통신규칙을 의미한다.

클라이언트와 서버가 주고받는 request와 response를 나타낸다.

request에는 get, post,put,delete등이 있고 response에는 200(성공), 400~(에러)등의 실행결과 코드가 있다.

 

const http = require('http')

//create a server object:
http.createServer(function (req, res) {
    res.write('hello world') //write a response to the client
    res.write(req.url) //read url that comes after domain name
    res.end('eeeeeee') //end the response
 })
 .listen(8080) //the server object listens on port 8080

 

API를 만들어보자

HTTP Request는 웹서버에 데이터를 요청하거나 전송할때 보내는 패킷으로 Get,Post메소드등을 활용한다.

GET의 경우 웹브라우저에 요청 데이터에 대한 인수를 URL을 통해 전송한다.

게시글목록 보기인 /posts와 게시글보기 /posts/:id로 구분하기로한다.

//GET
//게시글목록
localhost:8080/posts
//세부 게시글보기
localhost:8080/posts/2

 

POST의 경우 게시글작성으로 GET의 /posts와 동일하나 POST방식에서는 인수 값을 URL을 통해 전송하지않기 때문에

다른이가 링크를 통해 해당 페이지를 볼 수 없다는 것을 참고하고 차차 배워나가도록한다.

 

const http = require('http')

const idRegEx = /^\/posts\/([a-zA-Z0-9-_]+)$/

//create a server object:
http.createServer(function (req, res) {
    if (req.url === '/posts' && req.method === 'Get') {
    res.statusCode = 200
    res.end('List of Posts')
  } else if (req.url && idRegEx.test(req.url)) {
    res.statusCode = 200
    res.end('Content of the Posts')
  } else if (req.url === '/posts' && req.method === 'Post') {
    res.statusCode = 200
    res.end('Creating post')
  } else {
    res.statusCode = 404
    res.end('Not found')
  }
 })
 .listen(8080) //the server object listens on port 8080

test()메소드는 정규식이 맞는지 틀린지 boolean값만 리턴한다.

exe()메소드는 맞았는데 구체적으로 어떻게 맞았는지 정보를 돌려줌.

    console.log(idRegEx.exec(req.url))

  여기서 우리는 '2'만필요하므로 idRegEx.exec(req.url)[1]번 값만 사용하기로하고 postId를 변수명으로 짓자

 

다음 포스팅에서는

데이터를 대신할 객체를 만들고

post와 get을 각각 채워 간단한 블로그포스팅을 완성한다.

반응형