๐Ÿฆ_21.12.30 TIL

qhflrnfl4324ยท2022๋…„ 1์›” 6์ผ
0
post-thumbnail

21๋…„ 12์›” 30์ผ

๐Ÿ“ ์ฝ”๋“œ๋ผ์ด์–ธ - ์ผ๋‹จ ๋งŒ๋“œ๋Š” node.js

๐Ÿ“ƒ Chapter_5 Express๋กœ ๊ฐœ๋ฐœ ํšจ์œจ์„ฑ ๋†’์ด๊ธฐ(2)

๐Ÿ“Ž Routing

Routing

  • ์š”์ฒญ์— ๋”ฐ๋ผ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ฃผ๋Š” ๊ฒƒ
  • routing์˜ ์ถœ๋ฐœ์ ์ธ app.js ํŒŒ์ผ์—์„œ
// app.js
var indexRouter = require("./routes/index");
app.use("/", indexRouter);
// '/'๋กœ ์š”์ฒญ์„ ๋ณด๋ƒˆ์„ ๋•Œ, ๋ผ์šฐํŒ…์„ ํ†ตํ•ด์„œ indexRouter๋กœ ์š”์ฒญ์„ ๋„˜๊ธฐ๊ฒ ๋‹ค๋Š” ์˜๋ฏธ
// index.js
var express = require("express");
var router = express.Router();

module.exports = routervar express = require("express");
var router = express.Router();

// ๋ผ์šฐํŒ…์˜ ์‹œ์ž‘์€ router
// .get, .post, .put, .delete ๋“ฑ http method๋ฅผ ํ™œ์šฉํ•ด์„œ
// 1์ฐจ์ ์œผ๋กœ method์— ๊ด€ํ•œ ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค.
router.get("/", (req, res) => {
  res.json({
    message: "์„ฑ๊ณต~",
  });
});

module.exports = router;

var express = require("express");
var router = express.Router();

router.get("/main", (req, res) => {
  res.json({
    message: "๋ฉ”์ธ๋„ ์„ฑ๊ณต~",
  });
});

module.exports = router;

  • HTTP Method๋ฅผ POST๋กœ ์„ ํƒํ•œ ํ›„ send๋ฅผ ๋ˆ„๋ฅด๋ฉด
    => Not Found ํ™•์ธ

  • ํ•ด๋‹น url์— ์ ‘๊ทผํ–ˆ์„ ๋•Œ, ์ฝœ๋ฐฑํ•จ์ˆ˜๋กœ ๋‚˜์˜ค๋Š” request์™€ response
    • request : ์š”์ฒญ์— ๋Œ€ํ•œ ๊ฐ์ฒด. ํด๋ผ์ด์–ธํŠธ์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๋„˜๊ฒจ์ค„ ๋•Œ ์„œ๋ฒ„ ์ธก์—์„œ ์ด๋ฅผ ๋ฐ›๊ธฐ ์œ„ํ•œ ์šฉ๋„๋กœ ์‚ฌ์šฉ
    • response : ์‘๋‹ต์— ๋Œ€ํ•œ ๊ฐ์ฒด
var express = require("express");
var router = express.Router();

router.post("/main", (req, res) => {
  console.log(req.body);
});

module.exports = router;

  • request ๊ฐ์ฒด์˜ body ์•ˆ์— ๋ฐ์ดํ„ฐ๊ฐ€ ๋‹ด๊ธด๋‹ค.
    => ์ด๋Ÿฌํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ์„œ๋ฒ„ ์ธก์—์„œ ๊บผ๋‚ด์™€์„œ ๋ณ€์ˆ˜๋‚˜ ์ƒ์ˆ˜ ์•ˆ์— ์ดˆ๊ธฐํ™” ์‹œ์ผœ์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก ๋งŒ๋“ฆ
{ data: 'data1' }
  • ๋Œ€ํ‘œ์ ์ธ ์ฝ”๋“œ
var express = require("express");
var router = express.Router();

router.post("/main", (req, res) => {
  const data = req.body.data;
  
  // send
  res.send("๋ฌธ์ž์—ด์ด ์‘๋‹ต๋ฉ๋‹ˆ๋‹ค!");
  // json
  res.json({
    message: "json ์‘๋‹ต",
  });
  // render
  res.render("index");
  
});

module.exports = router;

13๋ฒˆ

  • send : ๋ฌธ์ž์—ด์„ ์‘๋‹ตํ•  ์ˆ˜ ์žˆ์„ ๋•Œ ์‚ฌ์šฉ

  • json : json ๊ฐ์ฒด๋ฅผ ์‘๋‹ต

  • render : HTML ์ฝ”๋“œ๊ฐ€ ๋“ค์–ด๊ฐ„ ํ…œํ”Œ๋ฆฟ ํŒŒ์ผ์„ ์ง์ ‘ ๋ณผ ์ˆ˜ ์žˆ๋Š” ๋ทฐ ํŒŒ์ผ๋“ค์„ ๋ Œ๋”๋ง ํ•ด์คŒ
    => .ejs ํ™•์žฅ์ž๋ช… ์ œ์™ธํ•˜๊ณ  ์ž‘์„ฑ
    => HTML ์ฝ”๋“œ๋ฅผ ๋ธŒ๋ผ์šฐ์ €์— ๋ณด์—ฌ์ฃผ๋Š” ๋ฐฉ์‹
    => postman์—์„œ ๋ดค์„ ๋•Œ HTML ์ฝ”๋“œ๋กœ ๋ณด์ด์ง€๋งŒ Preview์—์„œ๋Š” ์•„๋ž˜ ๊ทธ๋ฆผ๊ณผ ๊ฐ™์ด "My first projuect"๊ฐ€ ๋ณด์—ฌ์ง„๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€