2021년 3월 23일 복기(chatterbox server)

Ji Taek Lim·2021년 3월 23일
0

Chatterbox server를 하는데 예전에 postman으로 요청하고 있었던것을 조금 적용해보았다.

저번 스프린트때는 클라이언트와 연결이 안되었는데

이번에는 연결이 되었다.

localhost:3000/messages로 연결을 해주었다.


const cors = require("cors");
const express = require("express");
const app = express();

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

const port = 3000;

// {
//     username: document.querySelector(".inputUser").value,
//     text: document.querySelector(".inputChat").value,
//     date: new Date().toLocaleString(),
//     roomname: document.querySelector(".inputRoomName").value,
//   },
const posts = [
  {
    username: "Anderson",
    text: "hi",
    date: "2021-03-23",
    roomname: "codestates",
  },
];

app.get("/messages", (req, res) => {
  const data = JSON.stringify(posts);
  res.end(data);
});

app.post("/messages", (req, res) => {
  const message = req.body;
  posts.push(message);
  res.end();
});

app.use((req, res, next) => {
  // 토큰 있니? 없으면 받아줄 수 없어!
  if (req.headers.token) {
    req.isLoggedIn = true;
    next();
  } else {
    res.status(400).send("invalid user");
  }
});

app.listen(port, () => {
  //   console.log(`Example app listening at http://localhost:${port}`);
});

authentification도 있고

socket이랑

data를 저장소에 저장하는 fs.readfile을 하고 싶은데 이걸 어떻게 해야할지 고민하고있다.

8.5: Saving Data to JSON File with Node.js - Programming with Text

https://www.youtube.com/watch?v=6iZiqQZBQJY&t=30s

var fs = require("fs");
var words = fs.readFileSync("words.json");


var fs = require("fs");
var data = fs.readFileSync("words.json");
var words = JSON.parse(data);

2.4 Saving to a Database - Working with Data and APIs in JavaScript

https://www.youtube.com/watch?v=xVYa20DCUv0&list=PLRqwX-V7Uu6YxDKpFzf_2D84p0cyk4T7X&index=12

var fs = require("fs");
var data = fs.readFileSync("words.json");
var words = JSON.parse(data);
console.log(words);

const express = require("express");
const app = express();
const port = 3000;

app.listen(port, listening);

function listening() {
  console.log(`Example app listening at http://localhost:${port}`);
}

app.use(express.static("website"));

app.get("/add/:word/:score?", addWord);

function addWord(request, response) {
  var data = request.params;
  var word = data.word;
  var score = Number(data.score);
  var reply;
  if (!score) {
    reply = {
      msg: "Score is required",
    };
  } else {
    words[word] = score;
    var data = JSON.stringify(words);
    fs.writeFile("words.json", data, finished);

    function finished(err) {
      console.log("all set");
    }

    reply = {
      msg: "THnk you for your work",
    };
  }

  response.send(reply);
}

app.get("/all", sendAll);

function sendAll(request, response) {
  response.send(words);
}

Programming from A to Z

https://shiffman.net/a2z/node-api/

MiddleWare

WEB3 - Express - 9.1. 미들웨어의 사용 - body parser
https://www.youtube.com/watch?v=-FG3iUvDfTM

Express 미들웨어

https://expressjs.com/ko/resources/middleware.html

body-parser

http://expressjs.com/en/resources/middleware/body-parser.html

https://www.youtube.com/watch?v=nySS7ILaSQU

const express = require("express");
const cors = require("cors");
const app = express();

const bodyParser = require("body-parser");
// const jsonParser = bodyParser.json();

// var fs = require("fs");
// var data = fs.readFileSync("posts.json");
// var posts = JSON.parse(data);

app.use(cors());
app.use(bodyParser());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

const port = 3000;

// {
//     username: document.querySelector(".inputUser").value,
//     text: document.querySelector(".inputChat").value,
//     date: new Date().toLocaleString(),
//     roomname: document.querySelector(".inputRoomName").value,
//   },
// const posts = [
//   {
//     username: "Anderson",
//     text: "hi",
//     date: "2021-03-23",
//     roomname: "codestates",
//   },
// ];

const posts = [{}]

app.get("/messages", (req, res) => {
  res.status(200).json({
    results: posts,
  });
});

// app.get("/messages", (req, res) => {
//   res.status(200).send(data);
// });

app.post("/messages", (req, res) => {
  const message = JSON.stringify(req.body);
  posts.push(message);
  res.status(201).send(message);
});
// app.post("/messages", jsonParser, (req, res) => {
//   const input = req.body;
//   data.results.push(input);
//   res.status(201).send(JSON.stringify(input));
// });

app.use((req, res, next) => {
  // 토큰 있니? 없으면 받아줄 수 없어!
  if (req.headers.token) {
    req.isLoggedIn = true;
    next();
  } else {
    res.status(404).send("invalid user");
  }
});

app.listen(port, () => {
  //   console.log(`Example app listening at http://localhost:${port}`);
});

module.exports = app;

오늘한 코드인데 1개 빼고는 테스트 케이스는 통과과 되었다.

fs.readfile이랑 socket이랑 authentification은 지금 하고 있다.

https://www.youtube.com/watch?v=7iQLkJ3rEQo

JSON Crash Course
https://www.youtube.com/watch?v=wI1CWzNtE-M

https://www.youtube.com/watch?v=WDrU305J1yw&list=RDCMUCSJbGtTlrDami-tDGPUV9-w&start_radio=1&t=12

https://www.youtube.com/watch?v=g8-Xrpl_Uhk&list=RDCMUCSJbGtTlrDami-tDGPUV9-w&index=3

fs.readFile

https://www.youtube.com/watch?v=2Ntnlv-nuV8

profile
임지택입니다.

0개의 댓글