묻고 답해요
129만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
해결됨[리뉴얼] Node.js 교과서 - 기본부터 프로젝트 실습까지
미들웨어 관련 질문입니다.
조현영님 강좌를 보던 중 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는 문제없이 잘 실행될겁니다. 하지만 제가 원하는 코드는 아닙니다. 그 밖에 문제점이 있다면 피드백 부탁드립니다.
-
미해결탄탄한 백엔드 NestJS, 기초부터 심화까지
next()가 없는 (불필요한) 경우에도, middleware 함수라고 볼 수 있나요??
안녕하세요~ 좋은 강의 넘 잘 듣고 있습니다~ 감사합니다 :) 이 에러 핸들링을 하는 함수를 middleware라고 언급해주셨는데, 저는 조금 헷갈려서 질문 드립니다! app.use((req: express.Request, res: express.Response, next: express.NextFunction) => { console.log('this is error middleware'); res.send({ error: '404 not found error' }); }); 미들웨어는 하려는 일의 중간에서, 개발자가 원하는 무언가를 할 수 있도록 하는 것을 말하는거니까 express 에서는 next() 가 있는 경우를 middleware 로 본다 는 것으로 이해했습니다. 그런데 위 코드는 다음으로 넘기는 것 없이 바로 404를 반환해서, next가 꼭 필요하지 않은 것 같은데... 이 경우에도 이 함수를 middleware 함수라고 볼 수 있나요~?
-
미해결실전 리액트 프로그래밍
질문있습니다.
sotre.js 부분의 sagaMiddleware.run(rootSaga) 에서 sagaMiddleware.run(searchSaga) 로 바로 사용하지 않고 rootSata 를 만든 이유는 여러개의 미들웨어를 관리할 수 있도록 하기 위해 한 것 인가요?