블록체인 구현해 보기 (3) - 서버 생성 (feat. Nodejs)

최현석·2022년 1월 4일
0

블록체인

목록 보기
5/5

이전 포스트에서 만든 블록들을 서버에서 확인할 수 있도록 올려보겠습니다.

필요한 모듈

  • express
  • body-parser

모듈 불러오기 및 선언

//httpServer.js
const express = require('express')
const bodyParser = require('body-parser')
const {getVersion,nextBlock,getBlocks} = require('./chainedBlock')
const {addBlock} = require('./checkValidBlock')

이전 포스트에서 만들었던 모듈들 중에 필요한 것들도 가져오겠습니다

서버 생성 및

const http_port = process.env.HTTP_PORT || 3001;

function initHttpServer() {
    const app = express();
    app.use(bodyParser.json());

    // /blocks
    app.get("/blocks", (req, res) => {
        res.send(getBlocks());
    });

    // block 생성
    app.post("/mineBlock", (req, res) => {
        const data = req.body.data || [];
        const block = nextBlock(data);
        addBlock(block);
        res.send(block);
    });

    // 버전 확인
    app.get("/version", (req, res) => {
        res.send(getVersion());
    });

    // 서버 중단
    app.post("/stop", (req, res) => {
        res.send({ msg: "Stop Server" });
        process.exit();
    });

    app.listen(http_port, () => {
        console.log("Listening Http Port : ", http_port);
    });
}

initHttpServer();
  • 3001번 포트를 사용하여 들어갈 수 있게 끔 하였습니다. /version에 들어오면 해당 블록의 버전과 /blocks에 들어오면 해당 블록의 제네시스 블록을 확인할 수 있습니다.

  • 따로 post 란을 만들지 않아서 CMD에서 post 작업을 해주겠습니다.
    • curl -H "Content-type: application/json" --data "{\"data\":[\"Anything1\",\"Anything2\"]}" -X POST [http://localhost:3001/mineBlock](http://localhost:3001/mineBlock) post 이후 다시 blocks에 들어오면 잘 들어오는 것을 확인할 수 있습니다.
profile
개발자 꿈나무 https://github.com/Tozinoo

0개의 댓글