Nodejs에서 api서버 만들기(postman)

Wonju·2022년 2월 22일
0
  1. 개발환경을 만들어 준다. express를 설치하고 서버 포트를 지정.
const express = require("express");
const app = express();

const server = app.listen(3001, () => {
  console.log("Start Server: localhost: 3001");
});
// URL에 콜론(:)이 있는 path에는 어떤 값이든 들어올 수 있다.
// 콜론이 있는 path에 들어오는 값을 인자로 사용할 수 있다.
app.get("/api/users/:type", async(req,res)=>{
  // 전송하고자하는 인자 type을 선언해준다.
  let {type} = req.params;
  // type이 "seoul"일 경우 아래와 같은 data를 send()해준다.
  if(type === "seoul"){
  let data = [
    {name: "홍길동", city: "seoul"},
    {name: "김철수", city: "seoul"},
  ];
  res.send(data);
  } else if (type === "jeju"){
  let data = [
    {name: "김영희", city: "jeju"},
    {name: "박지성", city: "jeju"},
  ];
  res.send(data);
  } else {
  res.send("Type is not defined.");
  }
});
  1. API 테스트 툴인 "Postman"을 통해 API서버가 잘 구동되는지 확인한다.

2-1. postman에 가입 후, workspace에서 내 서버를 테스트해본다.

뒤의 type을 "jeju"로 바꿔주면 당연히 jeju일 때 보여질 data들이 나타난다.

  1. https://www.npmjs.com/ 에서 uuid 패키지를 설치해 apikey를 생성하고, apikey가 일치할때만 data를 응답하도록 한다.
const express = require("express");
const app = express();
const uuidAPIKey = require("uuid-apikey");

const server = app.listen(3001, () => {
  console.log("Start Server: localhost: 3001");
});

const key = {
  apiKey: "DY85VAP-SEBPWND-MRVGA9F-D37BDH8",
  uuid: "6d934daa-tjw7-4c35-h533-0ki767cb43k4",
};

app.get("/api/users/:apikey/:type", async (req, res) => {
  let { type, apikey } = req.params;

  if (!uuidAPIKey.isAPIKey(apikey) || !uuidAPIKey.check(apikey, key.uuid)) {
    res.send("apikey is not valid.");
  } else {
    if (type === "seoul") {
      let data = [
        { name: "홍길동", city: "seoul" },
        { name: "김철수", city: "seoul" },
      ];
      res.send(data);
    } else if (type === "jeju") {
      let data = [
        { name: "박지성", city: "jeju" },
        { name: "김영희", city: "jeju" },
      ];
    } else {
      res.send("Type is not defined.");
    }
  }
});

참고: 개발자의 품격 유투브(https://www.youtube.com/watch?v=8XpVJaEWesM)

profile
안녕하세여

0개의 댓글