• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    해결됨

미들웨어 관련 질문입니다.

21.12.30 09:53 작성 조회수 118

0

조현영님 강좌를 보던 중 express와 미들웨어 관련된 강좌를 보고 express를 사용해 서버를 만들던 도중에 막히는 부분이 있어서 질문해봅니다. (단순 에러 해결 질문은 아닙니다.)
 
const axios = require("axios");
const express = require("express");
const path = require("path");
const morgan = require("morgan");
const app = express();
const hostName = "127.0.0.1";
const port = process.env.PORT || 5147;
require("./productServer1");

app.use(morgan("dev"));

function getInfoWithAxios(key) {
    if (key === "1") {
        res.sendFile(path.join(__dirname, "./productOne.html"));
    } else if (key === "2") {
        res.sendFile(path.join(__dirname, "./productTwo.html"));
    } else {
        res.sendFile(path.join(__dirname, "./productThree.html"));
    }
}

app.set("func", getInfoWithAxios());

app.get("/", (req, res) => {
    res.sendFile(path.join(__dirname, "./expressAPI.html"));
});

app.use("/product/:addr", (req, res, next) => {
    console.log(`you connect on ${req.params.addr}}`);
    next();
});

app.get("/product", (req, res) => {
    res.write("<h1>Here is product information</h1>");
    res.send();
});

app.get("/product/product1", async (req, res) => {
    try {
        const result = await axios.get("http://127.0.0.1:3257");
        const productID = String(result.data[0].id);
        app.get("func");
        console.log("Request Type:", req.method);
    } catch (err) {
        console.error(err);
    }
});

app.get("/product/product2", async (req, res) => {
    try {
        const result = await axios.get("http://127.0.0.1:3257");
        const productID = String(result.data[1].id);

        app.get("func");
        console.log("Request Type:", req.method);
    } catch (err) {
        console.error(err);
    }
});

app.get("/product/product3", async (req, res) => {
    try {
        const result = await axios.get("http://127.0.0.1:3257");
        const productID = String(result.data[2].id);

        app.get("func");
        console.log("Request Type:", req.method);
    } catch (err) {
        console.error(err);
    }
});

app.use((err, req, res, next) => {
    console.error(err);
    res.status(401).send(err.message);
});

app.listen(port, () => {
    console.log(`server is running at http://${hostName}:${port}`);
});
위에 코드를 실행시키면 우선 코드 본문의 내용이 실행됨과 동시에 require()로 productServer1이라는 express를 사용한 상품 데이터 서버가 실행됩니다. (localhost를 사용하고 상품 데이터 서버 포트는 3257)입니다. /product/product(1~3)으로 get메서드를 보내면 같이 실행되는 상품 데이터 서버에서 id값을 받아오고 id값을 getInfoWithAxios(key)함수에 넣어서 html페이지를 id값에 맞게 상품별로 분기하게 됩니다. 이떄 문제는 getInfoWithAxios()함수에 res객체가 없어서 id에 맞게 html페이지를 분기 할 수가 없다는 것입니다. 미들웨어로 처리를 하고 싶지만 방법을 모르겠어서 질문해봅니다. 그리고 app.get() 함수에 있는 각각의 productID를 어떻게 하면 매개변수로 대입 할 수 있는지도 궁금합니다. 요약하자면

함수를 미들웨어로 만들려면 어떻게 작성해야 하고 만든 함수를 접근할때 매개변수는 어떻게 대입할수 있을까요?

조현영님의 이해를 돕기 위해서 전체 프로젝트에 대한 깃 주소를 남겨드리겠습니다.

https://github.com/shere1765/node_server/tree/main/small_project

전체 프로젝트에 있는 expressAPI는 문제없이 잘 실행될겁니다. 하지만 제가 원하는 코드는 아닙니다.
그 밖에 문제점이 있다면 피드백 부탁드립니다.

답변 1

답변을 작성해보세요.

0

미들웨어 함수는 (req, res, next) => any 꼴입니다.

getInfoWithAxios(key, res) 이런 식으로 만드시면 됩니다. 꼭 미들웨어 함수로 만들 필요는 없고 res만 전달하시면 됩니다.

app.get('/product/:id', (req, res, next) => {
  req.params.id
})

:id 자리에 들어가는 값이 req.params.id가 됩니다.

getInfoWithAxios(req.params.id, res); 하면 됩니다.

이승훈님의 프로필

이승훈

질문자

2021.12.30

답변 감사드립니다. 덕분에 문제를 해결했습니다. 그런데 죄송한 말이지만 만약에 굳이 함수를 미들웨어로 만든다면 코드를 어떻게 짤수 있는지 여쭤봐도 될까요?

getInfoWithAxios를 말씀하시는 건가요? (req, res, next) => any 꼴이 미들웨어이니까 이렇게 만들어서 쓰시면 됩니다. getInfoWithAxios = (req, res, next) => { ... }

req를 전달했으니까 내부에서 req.params.id 접근 가능하고요.

이승훈님의 프로필

이승훈

질문자

2021.12.30

끝까지 답변달아주셔서 감사합니다. 굳이 미들웨어 꼴로 쓰지 않고 함수 형태로 써도 될거같네요.

감사합니다!