본문 바로가기
Javascript&Typescript/Node.js

[Node.js] Express

by clolee 2024. 1. 10.

app.js

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

app.listen(5000, () => {
  console.log("server is listening on port 5000...");
});

 

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

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

app.listen(5000, () => {
  console.log("server is listening on port 5000...");
});

app.all

모든 메서드(GET, POST, PUT, DELETE 또는 그 외의 것)에 대해 핸들러 실행. 

 

상태권한 추가

 res.status(404).send("<h1>resource not found</h1>");

 

 

 

 

 

 

 

path 합치기

path.resolve(path, ... ) : / 를 만나면 절대경로로 처리. 이전 path들은 무시함

path.join은 /를 상대경로로 처리

 

 

- param

 

- query

app.get("/api/v1/query", (req, res) => {
  const { search, limit } = req.query;
  let sortedProducts = [...products];

  if (search) {
    sortedProducts = sortedProducts.filter((product) => {
      return product.name.startsWith(search);
    });
  }
  if (limit) {
    sortedProducts = sortedProducts.slice(0, Number(limit));
  }
  res.status(200).json(sortedProducts);
});

 

- app.use

 

authorize.js

const authorize = (req, res, next) => {
  const { user } = req.query;
  if (user === "john") {
    req.user = { name: "John", id: 3 };
    next();
  } else {
    res.status(401).send("Unauthorized");
  }
};

module.exports = authorize;

 

app.js

const express = require("express");
const app = express();
const logger = require("./logger");
const authorize = require("./authorize");

app.use([logger, authorize]);

app.get("/", (req, res) => {
  res.send("Home");
});
app.get("/about", (req, res) => {
  res.send("About");
});
app.get("/api/products", (req, res) => {
  res.send("Products");
});
app.get("/api/items", (req, res) => {
  console.log(req.user);
  res.send("Items");
});

app.listen(5000, () => {
  console.log("Server is listening on port 5000....");
});

 

 

 

user === 'john'이므로 authorize에서 조건 충족.

next() 실행 -> app.get('/' ...)

 

 

 

 

 

 

 

 

참고 :

https://expressjs.com/en/guide/routing.html

https://velog.io/@thyoondev/Path.join%EC%99%80-Path.resolve-%EC%B0%A8%EC%9D%B4

 

 

댓글