inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

[리뉴얼] Node.js 교과서 - 기본부터 프로젝트 실습까지

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

해결된 질문

217

이승훈

작성한 질문수 49

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는 문제없이 잘 실행될겁니다. 하지만 제가 원하는 코드는 아닙니다.
그 밖에 문제점이 있다면 피드백 부탁드립니다.

express middleware nodejs node.js mongodb javascript mysql Sequelize

답변 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); 하면 됩니다.

0

이승훈

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

0

제로초(조현영)

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

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

0

이승훈

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

감사합니다!

리눅스 노드 설치시 패키지

0

172

0

socket.js 에서 referer로부터 roomId를 가져올 때

0

926

3

스트리밍 방식으로 대용량 파일 업로드 & 다운로드 관련 질문

0

2297

2

a[title] 질문드립니다

0

386

1

리뉴얼 강의 및 공부 방법

0

589

1

jwt decode

0

1138

1

node.js 교과서 3판 질문드립니다

0

397

1

passport와 jwt

0

438

1

리뉴얼 강의

0

428

2

혹시 Node.js 교과서 3판 이북은 언제 나오나요?

0

359

1

몽고디비 사용자도 MYSQL부분을 들어야 하나요???

0

490

1

sql 쿼리 로그는 어떤 모듈이 작성하나요?

0

511

2

nunjucks res.render('error'); 작동을 안합니다.

0

518

1

질문있습니다.

0

348

1

multer 한글 파일 업로드시 파일명이 깨져요.

1

3543

1

수업자료는 어디있나요?

0

374

1

질문 있습니디

0

245

1

multer 사용시 file 외 name값은 못받나용?

0

430

1

코드 중복 부분 질문드립니다.

0

303

1

api 만드는 이유 질문드립니다.

0

293

1

Strategy의 done에 대해 질문드립니다.

0

374

1

안녕하세요 fs 권한 관련 질문드립니다

0

456

1

시퀄라이즈 연결질문...

0

510

2

res.setHeader vs res.cookie

0

1797

3