묻고 답해요
130만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
서버 실패시, 패스포트 로그인 실패시 통합테스트 방법
exports.login = (req, res, next) => { passport.authenticate('local', (authError, user, info) => { // 1. 서버 실패 부분 if (authError) { console.error(authError); return next(authError); } if (!user) { return res.redirect(`/?error=${info.message}`); } return req.login(user, (loginError) => { //2. 패스포트 로그인 실패 if (loginError) { console.error(loginError); return next(loginError); } return res.redirect('/'); }); })(req, res, next); }; --------------------- 1번과 2번은 통합테스트 코드로 어떻게 테스트 코드를 작성해야 하는지 여쭤봐도 될까요? 1번은 try - catch 로 어떻게 해보려해도 생각이 안나용 2번은 아애 생각이 안납니다 ㅜㅜ controllers를 자체를 단위테스트를 하는 것이 아니라 분기마다 test를 작성하라고 하신 말씀에 이 부분은 통합테스트로 코드를 짤 수 있나 의문이 들어서요! 감사합니다
-
미해결파이썬 Streamlit 활용한 웹 자동화 업무, 데이터 검색 및 시각화
강의 자료 링크(노션) 자료
안녕하세요, 강사님보안 프로젝트들을 유용하게 잘 듣고 있는 수강생입니다.항상 좋은 자료 강의 컨텐츠 올려 주셔서 감사드립니다.다름이 아니라 강의 자료 받고 싶어서강의 자료 링크(노션) 클릭을 했는데, '페이지를 찾을 수 없음' 뜨면서 강의 다운로드를 못 받고 있습니다.어떻게 하면 다운로드 받을 수 있는지요?바쁘시겠지만 확인 부탁드립니다!감사합니다.
-
미해결[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
7.5 시퀄라이즈 사용하기 에러
7.5 시퀄라이즈 사용하기 강좌 부분입니다.피피티와 동일하게 작성했는데 sync에러가 자꾸 뜹니다. 어떻게 고쳐야할지 모르겠습니다. app.jsconst express = require('express'); const path = require('path'); const morgan = require('morgan'); const nunjucks = require('nunjucks'); const { sequelize } = require('./models'); const app = express(); app.set('port', process.env.PORT || 3001); app.set('view engine', 'html'); nunjucks.configure('views', { express: app, watch: true, }); sequelize.sync({ force: false }) .then(() => { console.log('데이터베이스 연결 성공'); }) .catch((err) => { console.error(err); }); app.use(morgan('dev')); app.use(express.static(path.join(__dirname, 'public'))); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use((req, res, next) => { const error = new Error(`${req.method} ${req.url} 라우터가 없습니다.`); error.status = 404; next(error); }); app.use((err, req, res, next) => { res.locals.message = err.message; res.locals.error = process.env.NODE_ENV !== 'production' ? err : {}; res.status(err.status || 500); res.render('error'); }); app.listen(app.get('port'), () => { console.log(app.get('port'), '번 포트에서 대기 중'); }); index.jsconst Sequelize = require('sequelize'); const env = process.env.NODE_ENV || 'development'; const config = require('../config/config')[env]; const db = {}; const sequelize = new Sequelize(config.database, config.username, config.password, config); db.seqelize = sequelize; module.exports = db;error ->[nodemon] restarting due to changes...[nodemon] starting node app.jsC:\Users\jyoun\udr_node\lecture\app.js:15sequelize.sync({ force: false }) ^TypeError: Cannot read properties of undefined (reading 'sync') at Object.<anonymous> (C:\Users\jyoun\udr_node\lecture\app.js:15:11) at Module._compile (node:internal/modules/cjs/loader:1241:14) at Module._extensions..js (node:internal/modules/cjs/loader:1295:10) at Module.load (node:internal/modules/cjs/loader:1091:32) at Module._load (node:internal/modules/cjs/loader:938:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12) at node:internal/main/run_main_module:23:47Node.js v20.7.0[nodemon] app crashed - waiting for file changes before starting... [제로초 강좌 질문 필독 사항입니다]질문에는 여러분에게 도움이 되는 질문과 도움이 되지 않는 질문이 있습니다.도움이 되는 질문을 하는 방법을 알려드립니다.https://www.youtube.com/watch?v=PUKOWrOuC0c0. 숫자 0부터 시작한 이유는 1보다 더 중요한 것이기 때문입니다. 에러가 났을 때 해결을 하는 게 중요한 게 아닙니다. 왜 여러분은 해결을 못 하고 저는 해결을 하는지, 어디서 힌트를 얻은 것이고 어떻게 해결한 건지 그걸 알아가셔야 합니다. 그렇지 못한 질문은 무의미한 질문입니다.1. 에러 메시지를 올리기 전에 반드시 스스로 번역을 해야 합니다. 번역기 요즘 잘 되어 있습니다. 에러 메시지가 에러 해결 단서의 90%를 차지합니다. 한글로 번역만 해도 대부분 풀립니다. 그냥 에러메시지를 올리고(심지어 안 올리는 분도 있습니다. 저는 독심술사가 아닙니다) 해결해달라고 하시면 아무런 도움이 안 됩니다.2. 에러 메시지를 잘라서 올리지 않아야 합니다. 입문자일수록 에러메시지에서 어떤 부분이 가장 중요한 부분인지 모르실 겁니다. 그러니 통째로 올리셔야 합니다.3. 코드도 같이 올려주세요. 다만 코드 전체를 다 올리거나, 깃헙 주소만 띡 던지지는 마세요. 여러분이 "가장" 의심스럽다고 생각하는 코드를 올려주세요.4. 이 강좌를 바탕으로 여러분이 응용을 해보다가 막히는 부분, 여러 개의 선택지 중에서 조언이 필요한 부분, 제 경험이 궁금한 부분에 대한 질문은 대환영입니다. 다만 여러분의 회사 일은 질문하지 마세요.5. 강좌 하나 끝날 때마다 남의 질문들을 읽어보세요. 여러분이 곧 만나게 될 에러들입니다.6. 위에 적은 내용을 명심하지 않으시면 백날 강좌를 봐도(제 강좌가 아니더라도) 실력이 늘지 않고 그냥 코딩쇼 관람 및 한컴타자연습을 한 셈이 될 겁니다.
-
미해결[웹 개발 풀스택 코스] Node.js 프로젝트 투입 일주일 전 - 기초에서 실무까지
그럼 그걸 다 들어야 하나요?
다른 강의에 테이블이 있다고 해서 가보니..파일로 있는 게 아니고 화면에 있던데..그러면 저 처럼 그런 강의가 필요 없는 사람은..그걸 다 보고 만들라는 건가요? 그러기엔 시간이 아까운데요?하루죙일..개발 하다가 왔는데..그걸 보고 일일이 쳐서 만들라는 건 좀 아니지 않나요?
-
미해결mongoDB 기초부터 실무까지(feat. Node.js)
$elemMatch 질문이 있습니다.
값을 찾을 때 $elemMatch 로 감싸줘야 둘 다 해당하는 값을 찾을 수 있다고 해주셨는데요.반대로, $elemMatch 를 쓰지 않으면 or 조건으로 검색이 된다고 이해했습니다. 여기서위와 같은 필터로 값을 검색 했을 때 username 이 Henry5522 이거나, title 이 ullam esse dolorem 인 모든 값이 필터 결과로 나와야 하는게 아닌가요?
-
해결됨mongoDB 기초부터 실무까지(feat. Node.js)
DB 업데이트에 실패했을 상황에서 대처는 어떻게 할 수 있나요.
await Promise.all([ comment.save(), Blog.updateOne({ _id: blogId }, { $push: { comments: comment } }), ]);위 코드에서comment.save() 는 정상적으로 동작해서 DB 에 입력이 되었지만 Blog.updateOne 은 알수 없는 오류로 실패가 떨어졌다면,데이터에 싱크가 맞지 않을 수 있을거 같은데요. comment.save 했던걸 되돌리거나 하는 처리가 있어야 할 거 같은데, 어떻게 처리할 수 있나요?
-
미해결mongoDB 기초부터 실무까지(feat. Node.js)
블로그에 user 데이터를 추가하는 방법에 대해서
읽는 시점에 populate 부분에 대한 시간도 최소화 하기 위해서 생성하는 시점에 user 의 최소한의 데이터를 넣어주고 있는거 같은데요.이렇게 접근하면, 화면 중심으로 모델이 설계가 되는게 아닐까요?요구사항이 바뀌거나, 다른 서비스에서 해당 API 를 사용하게 되면 매번 모델을 수정하고 데이터를 마이그레이션 해야 하는 이슈가 생길 수 있을거 같은데요.어떻게 생각하시나요?
-
미해결mongoDB 기초부터 실무까지(feat. Node.js)
blog 데이터 생성시 user 관련 오류
블로그 생성할 때 user 객체를 넣으면, 리턴 값으로 user 객체를 받을 수 있는 이점이 있다고 해서, 전달해봤는데요.아래와 같은 에러가 발생합니다.blog validation failed: user: Cast to ObjectId failed for value블로그 생성시 user 가 아닌 userId 를 전달하면 정상적으로 블로그가 생성되나, 리턴값에는 user 객체가 아닌 userId 가 매핑되어 있습니다.mongoose 버전이 올라가면서 변경된 사항이 있어서 발생한 이슈일까요?
-
해결됨mongoDB 기초부터 실무까지(feat. Node.js)
age 예외 처리를 별도로 하신 이유가 궁금합니다.
이미 Schema 정의 할 때 age 를 number 로 했기 때문에, 디비에 저장할 때 number 값을 전달하지 않으면 에러가 발생해서 catch 에서 처리할 수 있을거 같은데요.업데이트 전에 필드를 validation 하면 모든 필드에 대해서 일일히 다 해줘야 할 것 같은데, 그렇게 하는 이유가 있을까요?그리고, catch 에러에서 number 값을 입력하지 않아서 발생한 오류임을 알 수 있는 방법(e.g., 에러 코드)이 있나요?
-
미해결mongoDB 기초부터 실무까지(feat. Node.js)
delete 메소드가 많은 이유가 궁금합니다.
User.findOneAndDelete User.deleteOne User.findByIdAndDelete이렇게 많은 인터페이스를 제공해주는 이유가 있을까요?단순히 편의를 위한 것인지, 상황에 따라 골라쓰는게 성능적으로 좋은 것인지 궁금합니다.
-
미해결mongoDB 기초부터 실무까지(feat. Node.js)
unique validation 처리
unique 에서 중복이 발생하면 catch 에 잡히는데, 이 때 unique 에러 때문에 발생한 에러인지 어떻게 알고 케이스를 나눠서 클라이언트에게 전달 할 수 있을까요?
-
미해결[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
NODE로 프로그램을 WINDOW 설치 프로그램으로 만들고싶습니다.
제가 만든 NODEJS 프로그램을 한글처럼 WINDOW 환경에서 통합설치 프로그램 하나만 설치하면 DB, NODE 프로그램이 설치되도록 하고싶은데 어떤 방법이 있고 구글에 어떻게 검색해야 하는지 궁금합니다.
-
해결됨[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
sequelize initiate() 쓰는 방식 최신인지, 공식문서 방법인지 궁금합니다
영상에서는 sequelize 공식문서에서 바뀌어서 따라갔다고 하는데 공식문서에서 initiate() 쓰는 것 검색하였을 때 안보이며 static이랑 같이 쓴 것도 아직은 못찾았습니다 공식문서 따라가보면 주로 define(), init()을 쓰는데 강의영상의 방식과는 차이점이 있습니다.define()const { Sequelize, DataTypes } = require('sequelize'); const sequelize = new Sequelize('sqlite::memory:'); const User = sequelize.define('User', { // Model attributes are defined here firstName: { type: DataTypes.STRING, allowNull: false }, lastName: { type: DataTypes.STRING // allowNull defaults to true } }, { // Other model options go here }); // `sequelize.define` also returns the model console.log(User === sequelize.models.User); // trueinit()// Invalid class User extends Model { id; // this field will shadow sequelize's getter & setter. It should be removed. otherPublicField; // this field does not shadow anything. It is fine. } User.init({ id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true } }, { sequelize }); const user = new User({ id: 1 }); user.id; // undefined 강의에서 알려주는 방식으로 DB연결도 되고 조작도 잘되지만이렇게 질문을 남긴 이유는강의에서는 공식문서를 따라갔다고 하는데 공식문서에서는 찾기 어렵다는 점과강의에 나오는 방식이 시기가 지난 방법이 아닐까 하는 생각에 질문 남기게 되었습니다 제가 찾아본게 잘못된걸수도 있기에 그런점 있다면 알려주세요글읽어주셔서 고맙습니다:)
-
미해결따라하며 배우는 노드, 리액트 시리즈 - 유튜브 사이트 만들기
npm run dev 실행 오류
Should not import the named export 'version' (imported as 'version') from default-exporting module (only default export is available soon) npm run dev를 실행했더니 이런 오류가 떠요.....도와주세요ㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜㅜ
-
미해결MERN 스택으로 만드는 지도서비스(+ TypeScript)
지도가 두개가 열리는 것 같습니다
보시면 하나의 지도 div에 두개가 열리는 것 같습니다.실제로 지도가 두개가 열려 서로 level이 달라 겹치는 모습입니다. 뒷장의 지도에는 마커가 표기되지 않습니다.아래는 맵과 관련된 코드들입니다.mern_client/src/components/common/Map/index.tsximport React, { useEffect } from 'react'; interface MapProps { width: string; height: string; initMap?: (map: naver.maps.Map) => void; } function Map({width, height, initMap}: MapProps) { useEffect(() => { const mapOptions = { center: new naver.maps.LatLng(37.3595704, 127.105399), zoom: 10 }; const map = new naver.maps.Map('map', mapOptions); if (initMap){ initMap(map); } }, []); return <div id="map" style={{width, height}}></div>; } export default Map; mern_client/src/components/MapContainer.tsximport { useSetAtom } from "jotai"; import React from 'react'; import Map from './common/Map'; import { mapAtom } from "../atoms/map"; function MapContainer() { const setMap = useSetAtom(mapAtom); const initMap = (map: naver.maps.Map) => { setMap(map); naver.maps.Event.addListener(map, 'click', () => { console.log("맵 클릭"); }); }; return <Map width="100%" height='100%' initMap={initMap}/> }; export default MapContainer; mern_client/src/atoms/map.tsimport { atom } from 'jotai'; export const mapAtom = atom<naver.maps.Map | null>(null);
-
미해결[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
AWS 배포 서버 관련 문의드립니다....
혹시 서버가 2개가 생성된 이유가 뭘까요..?
-
해결됨mongoDB 기초부터 실무까지(feat. Node.js)
updateMany에서 user._id를 못찾는 상황
강좌대로 Blog.updateMany({ "user._id": userId }, { "user.name": name })로 하니 블로그 데이터 유저 정보가 변경이 계속 안되고 있습니다 ㅠㅠ 유저 데이터는 정상적으로 변경이 되었는데요 문제점을 모르겠습니다.해당 코드 깃허브 : https://github.com/alinfanclub/KimDevlogServer/blob/updateMany/src/routes/userRouter.js userRouter.put("/:userId", async (req, res) => { try { const { userId } = req.params; if (!mongoose.isValidObjectId(userId)) return res.status(400).send({ err: "invalid userId" }); const { age, name } = req.body; if (!age && !name) return res.status(400).send({ err: "age or name is required" }); if (age && typeof age !== "number") return res.status(400).send({ err: "age must be a number" }); if (name && typeof name.first !== "string" && typeof name.last !== "string") return res.status(400).send({ err: "first and last name are strings" }); // let updateBody = {}; // if(age) updateBody.age = age; // if(name) updateBody.name = name; // const user = await User.findByIdAndUpdate(userId, updateBody, { new: true }); let user = await User.findById(userId); if (age) user.age = age; if (name) { user.name = name; await Blog.updateMany({ "user._id": userId }, { "user.name": name }); } await user.save(); return res.send({ user }); } catch (err) { console.log(err); return res.status(500).send({ err: err.message }); } });
-
미해결[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
SSH 콘솔 sql 설치 오류문의합니다.
sudo dpkg -i mysql-apt-config_0.8.23-1>_all.deb를 입력하면 error가 발생하는데.. 어떻게 해결할 수 있을까요..?
-
미해결따라하며 배우는 노드, 리액트 시리즈 - 쇼핑몰 사이트 만들기[전체 리뉴얼]
[plugin:vite-plugin-eslint] error 'React' is defined but never used no-unused-vars
eslint 와 관련된 에러 인 것 같은데요.물론 강의 중에 말씀하신 eslint 설정도 완료 하였습니다. React를 사용하지 않는데 React를 import 해서 그런것 같습니다. 강사님 강의 중에는 이런 현상이 없는데 이런 현상이 나와서 구글링을 해보아도 뾰족한 답을 못찾았습니다.확인 부탁드립니다~!!
-
미해결따라하며 배우는 노드, 리액트 시리즈 - 유튜브 사이트 만들기
비디오 업로드, 로그인, 회원가입 504 error
안녕하세요 http://localhost:3000/video/upload 실행해 비디오를 선택하면 POST http://localhost:3000/api/video/uploadfiles 504 (Gateway Timeout),http://localhost:3000/register실행해 가입을 하려하면POST http://localhost:3000/api/users/register 504 (Gateway Timeout)Uncaught (in promise) Error: Request failed with status code 504이런 에러가 나옵니다 vscode 에서는 Server Listening on 5000[0] MongoError: bad auth : authentication failed[0] at MessageStream.messageHandler (C:\Han\boilerplate-mern-stack-master\boilerplate-mern-stack-master\node_modules\mongoose\node_modules\mongodb\lib\cmap\connection.js:299:20) [0] at MessageStream.emit (node:events:520:28)[0] at processIncomingData (C:\Han\boilerplate-mern-stack-master\boilerplate-mern-stack-master\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:144:12) [0] at MessageStream._write (C:\Han\boilerplate-mern-stack-master\boilerplate-mern-stack-master\node_modules\mongoose\node_modules\mongodb\lib\cmap\message_stream.js:42:5) [0] at writeOrBuffer (node:internal/streams/writable:389:12)[0] at _write (node:internal/streams/writable:330:10)[0] at MessageStream.Writable.write (node:internal/streams/writable:334:10)[0] at TLSSocket.ondata (node:internal/streams/readable:754:22)[0] at TLSSocket.emit (node:events:520:28)[0] at addChunk (node:internal/streams/readable:315:12)[0] at readableAddChunk (node:internal/streams/readable:289:9)[0] at TLSSocket.Readable.push (node:internal/streams/readable:228:10)[0] at TLSWrap.onStreamRead (node:internal/stream_base_commons:190:23) {[0] ok: 0,[0] code: 8000,[0] codeName: 'AtlasError'[0] } ,Error: ffmpeg exited with code 4294967291: frame= 1 fps=0.0 q=-0.0 Lq=-0.0 q=-0.0 size=N/A time=00:00:00.00 bitrate=N/A dup=2 drop=0 speed= 0x [0] video:199kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown[0] Conversion failed![0][0] at ChildProcess.<anonymous> (C:\Han\boilerplate-mern-stack-master\boilerplate-mern-stack-master\node_modules\fluent-ffmpeg\lib\processor.js:182:22)[0] at ChildProcess.emit (node:events:520:28)[0] at Process.ChildProcess._handle.onexit (node:internal/child_process:291:12)[0] Waiting for the debugger to disconnect...[0] node:events:498[0] throw er; // Unhandled 'error' event[0] ^[0][0] MongooseError: Operation `users.findOne()` buffering timed out after 10000ms[0] at Timeout.<anonymous> (C:\Han\boilerplate-mern-stack-master\boilerplate-mern-stack-master\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:198:23)[0] at listOnTimeout (node:internal/timers:559:17)[0] at processTimers (node:internal/timers:502:7)[0] Emitted 'error' event on Function instance at:[0] at C:\Han\boilerplate-mern-stack-master\boilerplate-mern-stack-master\node_modules\mongoose\lib\model.js:5084:15[0] at processTicksAndRejections (node:internal/process/task_queues:78:11)[1] [HPM] Error occurred while trying to proxy request /api/users/auth from localhost:3000 to http://localhost:5000 (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)[0] [nodemon] app crashed - waiting for file changes before starting...[1] [HPM] Error occurred while trying to proxy request /api/users/auth from localhost:3000 to http://localhost:5000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)[1] [HPM] Error occurred while trying to proxy request /api/users/auth from localhost:3000 to http://localhost:5000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)[1] [HPM] Error occurred while trying to proxy request /api/users/register from localhost:3000 to http://localhost:5000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)[1] [HPM] Error occurred while trying to proxy request /api/video/getVideos from localhost:3000 to http://localhost:5000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)[1] [HPM] Error occurred while trying to proxy request /api/users/auth from localhost:3000 to http://localhost:5000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)[1] [HPM] Error occurred while trying to proxy request /api/users/auth from localhost:3000 to http://localhost:5000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)[1] [HPM] Error occurred while trying to proxy request /api/video/uploadfiles from localhost:3000 to http://localhost:5000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)[1] [HPM] Error occurred while trying to proxy request /api/users/auth from localhost:3000 to http://localhost:5000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)[1] [HPM] Error occurred while trying to proxy request /api/users/auth from localhost:3000 to http://localhost:5000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)[1] [HPM] Error occurred while trying to proxy request /api/users/register from localhost:3000 to http://localhost:5000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors) 이렇게 나옵니다어떻게 해결해야 할까요 깃허브 https://github.com/Hanboreum/boilerplate-mern-stack-master