묻고 답해요
131만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
softdelete는 어떤 식은 test 코드를 짜야할까요?
jest 를 이용하여 테스트코드를 짜고 있는데 처음이라 너무 어렵네요. softdelete는 어떤식으로 테스트코드를 짜야될까요?그리고 조인해서 결과 값을 뽑을 때 테스트코드를 어떻게 짜야할지 감이 안옵니다.구글링해도 자료가 별로 없네여...
-
해결됨[리뉴얼] React로 NodeBird SNS 만들기
리액트 쿼리 SSR 부분 질문있습니다.
강의 프로젝트를 제로초님 깃헙 코드 참고해서 리액트 쿼리로 다시 만들어 보는중인데요 회원가입 페이지에 SSR 적용하는 과정에서 다음과 같은 에러가 납니다. 코드를 보면//pages/signup.tsx export const getServerSideProps = async (context: GetServerSidePropsContext) => { const cookie = context.req ? context.req.headers.cookie : ''; axios.defaults.headers.Cookie = ''; if (context.req && cookie) { axios.defaults.headers.Cookie = cookie; } const response = await loadMyInfoAPI(); if (response.data) { return { redirect: { destination: '/', permanent: false, }, }; } return { props: {}, }; }; // api/user.ts export function loadMyInfoAPI() { return axios.get('/user').then((response) => response.data); } // routes/user.js router.get('/', async (req, res, next) => { try { if (req.user) { const fullUwerWithoutPassword = await User.findOne({ where: { id: req.user.id }, attributes: { exclude: ['password'] }, include: [ { model: Post, attributes: ['id'] }, { model: User, as: 'Followings', attributes: ['id'] }, { model: User, as: 'Followers', attributes: ['id'] }, ], }); res.status(200).json(fullUwerWithoutPassword); } else { res.status(200).json(null); } 로그인안한 상태에서 유저 정보를 불러오면 null이 반환되서 에러가 나는거 같은데요 const response = await loadMyInfoAPI(); if (response.data) { return { redirect: { destination: '/', permanent: false, }, }; } 이부분을 지우고 다음과 같이 바꿔주면export const getServerSideProps = async (context: GetServerSidePropsContext) => { const cookie = context.req ? context.req.headers.cookie : ''; axios.defaults.headers.Cookie = ''; if (context.req && cookie) { axios.defaults.headers.Cookie = cookie; } return { props: {}, }; }; 에러가 사라지는데 지워도 상관없는건가요??
-
해결됨Slack 클론 코딩[백엔드 with NestJS + TypeORM]
try문 밖에서 에러 발생시 트랜잭션이 release가 안됩니다.
12:00 시작된 join 매서드를 만들고 실행을 시켜보니 에러 처리를 하면 커넥션 pool이 종료되지 않는거 같습니다. 이메일이 중복된 user를 insert하려 할 때 new ForbiddenException이 실행이 됩니다. 하지만 finally문이 실행이 안되는거 같습니다.async join(email: string, nickname: string, password: string) { const queryRunner = this.dataSource.createQueryRunner(); await queryRunner.connect(); await queryRunner.startTransaction(); const user = await queryRunner.manager .getRepository(Users) .findOne({ where: { email } }); if (user) { throw new ForbiddenException('이미 존재하는 사용자입니다'); } const hashedPassword = await bcrypt.hash(password, 12); try { const returned = await queryRunner.manager.getRepository(Users).save({ email, nickname, password: hashedPassword, }); const workspaceMember = queryRunner.manager .getRepository(WorkspaceMembers) .create(); workspaceMember.User = returned.id; workspaceMember.Workspace = 1; // throw new NotFoundException('롤백해봐'); await queryRunner.manager .getRepository(WorkspaceMembers) .save(workspaceMember); await queryRunner.manager.getRepository(ChannelMembers).save({ User: returned.id, ChannelId: 1, }); await queryRunner.commitTransaction(); return true; } catch (error) { console.error(error); await queryRunner.rollbackTransaction(); throw error; } finally { console.log('이거 실행됨?'); await queryRunner.release(); } }'이거 실행됨?' 이라는 문자가 출력이 되지 않습니다. 여러번 반복한 후 pgAdmin에서 database activity를 살펴보니 커넥션 pool이 release되지 않고 idle 상태로 되어있습니다.이 때문에 서버의 pool이 가득차서 서버가 종료됩니다. user의 중복검사도 try문 안에 넣으면 해결되는거 같습니다. 🟩 혹시 존재하는 사용자 로직을 try문 밖에 빼신 이유가 있는지 궁금합니다.
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
nestjs+graphql로 작업할때 response도 dto로 만들어야하나요?
선생님, 질문두가지 드릴게요, 감사합니다1. nestjs+graphql로 작업할때 response도 dto로 만들어야하나요?2. class-validator를 entity에서 사용하고 dto를 pick, omit으로 상속받는게 좋나요? 아니면 dto들에서 따로 class-validator를 적용하는게 좋나요?
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
도커의 데이터베이스 컨테이너와 nestjs typeORM이 어떤 방식으로 연동되는지 궁금해요
docker-compose 에 있는 my-database의 연결app.module.ts에 있는 typeOrmModule에 있는 데이터베이스 연결이 어떤 원리로 작동되는지 궁금합니다. my-database: image: mysql:latest environment: MYSQL_DATABASE: 'mydocker' MYSQL_ROOT_PASSWORD: 'root' ports: - 3306:3306TypeOrmModule.forRoot({ //.env 파일은 모두 string 형태로 인식이 됩니다. 따라서, type과 port에 추가 설정을 해주었습니다. type: mysql, host: "localhost", port: 3306, username: "root", password: "12345678", database: practice, entities: [Board], synchronize: true, logging: true, })
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
CSS 정렬 강의 실습 중
코드 자동저장돼 있고 혹시몰라 수동저장 후 다시 라이브서버 켰는데 박스까지만 만들어지고 정렬이 전혀 되지 않으면서 아무 응답이 없는데 제가 혹시 코드를 잘못 쓴 부분이 있는걸까요?
-
해결됨Slack 클론 코딩[백엔드 with NestJS + TypeORM]
socket.io 사용 시 cors 에러 with react
안녕하세요 제로초님~! 최근에 socket.io 문제를 해결해주셔서 감사합니다. 제로초님 덕분에 몇주간 있었던 불면증이 사라졌습니다. 이번에 드리고자 하는 질문은 백엔드 api 서버와 리액트 로컬호스트의 websocket 연결에서 cors 에러가 사라지지 않고 있다는 것입니다.프론트와 백엔드 둘다 localhost로 사용했을땐 문제 없이 잘 작동하였으나, 백엔드 api 서버와 프론트(리액트) http://localhost:3000 로 연결하려 하니 cors 에러가 사라지질 않네요.백엔드 api 서버주소는 https://api.yubinhome.com/ 이고, traefik 을 사용해 https 인증을 받고 있습니다.제가 어떤 부분을 놓친 것인지 함께 봐주실 수 있을까요? 에러메시지 Access to XMLHttpRequest at 'http://api.yubinhome.com/socket.io/?EIO=4&transport=polling&t=Ohzm2CT' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. GET http://api.yubinhome.com/socket.io/?EIO=4&transport=polling&t=OhzmhTk net::ERR_FAILED 요청헤더 응답헤더 시도 해 본 방법1. 공식 문서에 나온대로 api url 에 직접 연결해보니 서버가 작동하고 있는 것은 확실해보입니다.소켓io 공식문서 cors : https://socket.io/docs/v3/handling-cors/#troubleshooting2. 서버측 origin, credetials 를 설정하였습니다. origin : "*" 가 문제인가 싶어 http://localhost:3000 url 을 직접 주었습니다. 클라이언트 측에는 withCredentials: true 을 설정해주었습니다.백엔드 api 서버 코드https://github.com/fog-of-war/dev-be/blob/dev/src/events/events.gateway.ts@WebSocketGateway({ cors: { origin: "http://localhost:3000", methods: ["GET", "POST"], allowedHeaders: ["authorization", "Authorization"], credentials: true, }, namespace: /\/ws-.+/, transports: ["websocket", "polling"], })리액트 코드https://github.com/fog-of-war/dev-fe/blob/46a8de3a13de4039e9aa511a07cfeea23d8a85fa/src/components/Notifications/NoticeNotifications.tsxREACT_APP_API_URL=https://api.yubinhome.com/REACT_APP_SOCKET_URL=ws://api.yubinhome.com/v1/ws-alertlet socket: any = null; socket = io(socketUrl + "-" + userId, { withCredentials: true, extraHeaders: { Authorization: `Bearer ${sanitizedToken}`, }, });
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
도커 컴포즈 질문드립니다
yml파일,mongo 파일,Dockerfile 만들고docker-compose builddocker-compose up 하고 다른 쉘에서docker ps했는데 아무것도 안뜹니다 파일은 제대로 따라 적었는데도 오류 뜨고 몽고 db는 삭제했고 몽고db 컴패스는 오류걸려서 그냥 삭제했습니다
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
로그인 프로세스 설명 중 질문
해당 장을 설명해주실 때 철수가 1050번째, 영희가 2050번째라고 가정했을때, 수직 파티셔닝 된 데이터베이스 중 어디에 있는지는 미리 알 수 있는 방법이 있을까요?
-
미해결탄탄한 백엔드 NestJS, 기초부터 심화까지
프론트엔드 코드 실행시 에러가 발생합니다.
>> 갱신, 2023. 10. 06해결했습니다.https://github.com/amamov/teaching-nestjs-a-to-z/tree/frontend위 링크 설명 따라 nestjs root 디렉토리에서 git clone 받고,npm install, npm run dev 하니까 잘 실행되네요$ npm run dev > frontend@0.1.0 dev > next start ready - started server on 0.0.0.0:3000, url: http://localhost:3000 info - Loaded env from C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\.env 잘못된 파일을 받았던것 같습니다..어느 질문글에서 본 링크 따라서 들어가서 받았던거로 기억하는데..어느 글이었는지 다시 찾아도 보이지 않네요.. >> 질문글, 2023. 10. 04학습자료 frontend를 다운 받았고, 이 폴더를 05 NestJS 실전 프로젝트와 같은 위치에 두었습니다.이후 프론트엔드 코드 실행 방법 강의를 보고frontend 디렉토리로 들어가 npm i를 입력하였습니다admin@DESKTOP-ALLM3V0 MINGW64 ~/OneDrive/바탕 화면/learning_NestJS/frontend (master) $ npm i npm WARN old lockfile npm WARN old lockfile The package-lock.json file was created with an old version of npm, npm WARN old lockfile so supplemental metadata must be fetched from the registry. npm WARN old lockfile npm WARN old lockfile This is a one-time fix-up, please be patient... npm WARN old lockfile npm WARN deprecated @types/antd@1.0.0: This is a stub types definition for antd (https://github.com/ant-design/ant-design). antd provides its own type definitions, so you don't need @types/antd installed! npm WARN deprecated @types/axios@0.14.0: This is a stub types definition for axios (https://github.com/mzabriskie/axios). axios provides its own type definitions, so you don't need @types/axios installed! npm WARN deprecated querystring@0.2.1: The querystring API is considered Legacy. new code should use the URLSearchParams API instead. npm WARN deprecated querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead. added 368 packages, and audited 369 packages in 24s 48 packages are looking for funding run `npm fund` for details 15 vulnerabilities (3 moderate, 7 high, 5 critical) To address issues that do not require attention, run: npm audit fix To address all issues (including breaking changes), run: npm audit fix --force Run `npm audit` for details.위와 같이 경고 메세지가 나왔고... 이 상태에서 npm run dev를 입력하였더니admin@DESKTOP-ALLM3V0 MINGW64 ~/OneDrive/바탕 화면/learning_NestJS/frontend (master) $ npm run dev > frontend@0.1.0 dev > next dev ready - started server on 0.0.0.0:3000, url: http://localhost:3000 info - Loaded env from C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\.env info - Using webpack 5. Reason: no next.config.js https://nextjs.org/docs/messages/webpack5 Error: error:0308010C:digital envelope routines::unsupported at new Hash (node:internal/crypto/hash:71:19) at Object.createHash (node:crypto:133:10) at BulkUpdateDecorator.hashFactory (C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:133790:18) at BulkUpdateDecorator.update (C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:133692:50) at OriginalSource.updateHash (C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack-sources2\index.js:1:19148) at NormalModule._initBuildHash (C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:65772:17) at handleParseResult (C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:65837:10) at C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:65928:4 at processResult (C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:65651:11) at C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:65711:5 Error: error:0308010C:digital envelope routines::unsupported at new Hash (node:internal/crypto/hash:71:19) at Object.createHash (node:crypto:133:10) at BulkUpdateDecorator.hashFactory (C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:133790:18) at BulkUpdateDecorator.update (C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:133692:50) at OriginalSource.updateHash (C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack-sources2\index.js:1:19148) at NormalModule._initBuildHash (C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:65772:17) at handleParseResult (C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:65837:10) at C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:65928:4 at processResult (C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:65651:11) at C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:65711:5 node:internal/crypto/hash:71 this[kHandle] = new _Hash(algorithm, xofLen); ^ Error: error:0308010C:digital envelope routines::unsupported at new Hash (node:internal/crypto/hash:71:19) at Object.createHash (node:crypto:133:10) at BulkUpdateDecorator.hashFactory (C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:133790:18) at BulkUpdateDecorator.update (C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:133692:50) at OriginalSource.updateHash (C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack-sources2\index.js:1:19148) at NormalModule._initBuildHash (C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:65772:17) at handleParseResult (C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:65837:10) at C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:65928:4 at processResult (C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:65651:11) at C:\Users\admin\OneDrive\바탕 화면\learning_NestJS\frontend\node_modules\next\dist\compiled\webpack\bundle5.js:65711:5 { opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ], library: 'digital envelope routines', reason: 'unsupported', code: 'ERR_OSSL_EVP_UNSUPPORTED' } Node.js v18.16.0위와 같은 에러가 발생하며 프론트엔드가 웹 서버가 실행되지 않고 있습니다..이러한 상황에서는 어떻게 진행하면 좋을지 조언 부탁드립니다.
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
productsSalesLocation.service create method
create({productSalesLocation}): Promise<ProductSalesLocation>{ return this.productsSalesLocationsRepository.save({...productSalesLocation}); }강의 중 위와 같은 코드를 작성해주셨는데, create의 parameter type은 ProductSalesLocation(Entity)의 타입에서 id만 제외하고 사용하는 형태로 작성하는 것이 맞을까요?
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
product entity의 deletedAt type
다음처럼 DeletedDateColumn 데코레이터를 붙인 deletedAt은 db에서 nullable이니까 optional 타입으로 하는 것이 맞을까요? @DeleteDateColumn()deletedAt?: Date; 공식 문서에서는 optional 타입으로 되어 있지는 않네요https://orkhan.gitbook.io/typeorm/docs/decorator-reference#deletedatecolumn
-
미해결[리뉴얼] React로 NodeBird SNS 만들기
안녕하세요. 게시글 필터링 관련해서 질문이있습니다.
안녕하세요. 현재 여러개의 select - option으로 게시된 게시글을 필터링을 해보려고 하고 있고 잘 작동하는데 코드가 너무 지저분합니다. 혹시 좀더 효율적으로 짤 수 있는 팁주실수 있으면 감사하겠습니다. ㅠㅠ const coursePosts = useSelector((state) => state.coursePost.coursePosts); const [group, setGroup] = useState("all"); const [subject, setSubject] = useState("all"); const [level, setLevel] = useState("all"); const fillteredCoursePosts = coursePosts.filter((post) => ( //문제의 부분 start group === 'all' && subject === 'all' && level === "all" ? post : subject === 'all' && level === "all" ? (post.group === group) : group === 'all' && level === "all" ? (post.subject === subject) : group === 'all' && subject === "all" ? (post.level === level) : group === "all" ? (post.subject === subject) && (post.level === level) : subject === "all" ? (post.group === group) && (post.level === level) : level === "all" ? (post.group === group) && (post.subject === subject) : (post.group === group) && (post.subject === subject) && (post.level === level) ) //문제의 부분 End ) const handleGroupChange = (e) => { setGroup(e.target.value); } const handleSubjectChange = (e) => { setSubject(e.target.value); } const handleLevelChange = (e) => { setLevel(e.target.value); } return ( <> <main className="width_content"> <div className={styles.course_box_wrap}> <div className={styles.filter_header}> <div className={styles.ft_select}> <select onChange={handleGroupChange}> <option value="all">ALL</option> <option value="Group1">Group 1</option> <option value="Group2">Group 2</option> <option value="Group3">Group 3</option> </select> <select onChange={handleSubjectChange}> <option value="all">ALL</option> <option value="English">English</option> <option value="Korean">Korean</option> </select> <select onChange={handleLevelChange}> <option value="all">ALL</option> <option value="Core">Core</option> <option value="test1">Embed</option> <option value="test2">Test</option> </select> </div> </div> </div> </main> </> ) }
-
해결됨따라하며 배우는 TDD 개발 [2023.11 업데이트]
[MAC] PORT:5000번 관련 에러
안녕하세요. PORT 5000으로 설정했더니이미 사용중인 포트로 나오더라구요.혹시 같은 증상 있으신 분 있으실 수 있을 것 같아서 남겨둡니다.맥 기준 시스템설정에서 '에어플레이 수신' 을 꺼주면 5000번 포트 사용할 수 있습니다.https://developer.apple.com/forums/thread/682332
-
미해결[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
레디스 에러
redis는 4.6.10 버전 쓰고 있고 connect-redis는 7.1.0 버전을 쓰고 있습니다. 레디스 코드를 깃허브에 업데이트 된 것 처럼 수정해 주었는데 로그인을 하려니 C:\Users\mikg2\Desktop\NodeBird-production\node_modules\@redis\client\dist\lib\client\RESP2\encoder.js:17 throw new TypeError('Invalid argument type'); ^ TypeError: Invalid argument type at encodeCommand (C:\Users\mikg2\Desktop\NodeBird-production\node_modules\@redis\client\dist\lib\client\RESP2\encoder.js:17:19) at RedisCommandsQueue.getCommandToSend (C:\Users\mikg2\Desktop\NodeBird-production\node_modules\@redis\client\dist\lib\client\commands-queue.js:138:45) at Commander._RedisClient_tick (C:\Users\mikg2\Desktop\NodeBird-production\node_modules\@redis\client\dist\lib\client\index.js:519:76) at Commander._RedisClient_sendCommand (C:\Users\mikg2\Desktop\NodeBird-production\node_modules\@redis\client\dist\lib\client\index.js:506:82) at Commander._RedisClient_legacySendCommand (C:\Users\mikg2\Desktop\NodeBird-production\node_modules\@redis\client\dist\lib\client\index.js:460:105) at Commander.sendCommand (C:\Users\mikg2\Desktop\NodeBird-production\node_modules\@redis\client\dist\lib\client\index.js:432:114) at <computed> [as set] (C:\Users\mikg2\Desktop\NodeBird-production\node_modules\@redis\client\dist\lib\client\index.js:478:27) at Object.set (C:\Users\mikg2\Desktop\NodeBird-production\node_modules\connect-redis\dist\cjs\index.js:24:34) at RedisStore.set (C:\Users\mikg2\Desktop\NodeBird-production\node_modules\connect-redis\dist\cjs\index.js:71:39) at Session.save (C:\Users\mikg2\Desktop\NodeBird-production\node_modules\express-session\session\session.js:72:25) Emitted 'error' event on Commander instance at: at C:\Users\mikg2\Desktop\NodeBird-production\node_modules\@redis\client\dist\lib\client\index.js:466:31 Node.js v18.16.0이런 에러가 뜨는데 버전 문제인가요? 모듈 내부적으로 발생한 거라 어디를 손봐야 할 지 모르겠습니다.참고로 세션 객체는Session { cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true, secure: false } }이렇게 찍혔습니다.
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
mySql DB 는 생성하였는데 테이블이 생성이 안되는 경우가 어떤 게 있을 까요?
윈도우로 하려니 참 수업이 쫒아가기 힘드네요.어찌 어찌 구글링으로 계속 진행하고 있는데요.도커로 올린 후 DB 는 생성을 했는데 테이블 생성이 안되네요. 2. localhost:4000 로 접속을 하면 화면이 보이지도 않구요. 아..도커 참 그렇네요. ^^: 이것 저것 손 댄 코드 입니다. 14 버전이 안되어서 16버전으로 변경# 컴퓨터 만드는 설명서 # 1. 운영체제 설치(node 14버전과 npm과 yarn이 모두 설치되어있는 리눅스) FROM node:16 # 2. 내 컴퓨터에 있는 폴더나 파일을 도커 컴퓨터 안으로 복사하기 COPY ./package.json /myfolder/ COPY ./yarn.lock /myfolder/ WORKDIR /myfolder/ RUN yarn install COPY . /myfolder/ # 3. 도커안에서 index.js 실행시키기 CMD yarn start:dev DB 포트 충돌로 3307번 확인 후 3306 번 접근version: '3.7' services: my-backend: build: context: . dockerfile: Dockerfile volumes: - ./src:/myfolder/src ports: - 4000:3000 env_file: - ./.env.docker my-database: platform: linux/x86_64 image: mysql:latest environment: MYSQL_DATABASE: 'mydocker' MYSQL_ROOT_PASSWORD: '0000' ports: - 3307:3306 도움 좀 부탁드립니다.
-
해결됨Slack 클론 코딩[백엔드 with NestJS + TypeORM]
socket.io 사용시 랜덤하게 객체가 emit 됩니다.
안녕하세요 제로초님~ 백엔드 개발자 지망생이자 제로초님의 팬인 신유빈입니다.1개월 가량 하기 문제를 구글링 하며 여러 경우의 수를 찾아보았지만 이유를 찾지 못하여 질문드립니다.질문드리고자 하는 내용은 이렇습니다.socket.io 로 이벤트를 emit 할때, 같은 메서드를 사용함에도 객체에 따라 클라이언트에 전송될 때도 있고, 전송되지 않을 때도 있는데 그 원인을 찾지 못하고 있습니다.현재 저는 신규게시물 혹은 댓글이 작성되었을때 모든 사용자에게 알림을 emit 하고자 합니다.현재 3가지의 경우 중 A만 성공중인 상태입니다.A : 테스트를 위하여 handleConnection 메서드에서 소켓에 연결한 사용자의 정보 객체를 message 로 전송시 성공B : 게시물 작성 시 생성한 알림 메시지 객체를 message 로 전송시 실패C: 댓글 작성 시 생성한 알림 메시지 객체를 message 로 전송시 실패모든 케이스에서 클라이언트에게 메시지를 성공적으로 보내려면 어떻게 해야할지 도움을 주실 수 있을까요?// 실행 동영상 https://youtu.be/AgLmcV53EvM// 코드깃허브 저장소 전체 코드https://github.com/fog-of-war/dev-be/blob/zerocho/README.mdEventsGatewayhttps://github.com/fog-of-war/dev-be/blob/zerocho/src/events/events.gateway.ts#L55 // fow-be/src/events/events.gateway.ts /** 웹소켓 연결시 */ handleConnection(@ConnectedSocket() socket: Socket, client: any) { const interval = setInterval(() => { const userInfo = socket.userInfo; this.sendMessage(userInfo); }, 5000); socket.on("disconnect", () => { clearInterval(interval); }); } /** 메시지 전송 */ sendMessage(message?: any) { console.log(" \n 🌠 sendMessage \n", message); this.server.emit("message", message); return Promise.resolve("Message sent successfully"); } AlertServicehttps://github.com/fog-of-war/dev-be/blob/zerocho/src/alert/alert.service.ts#L12 // fow-be/src/alert/alert.service.ts // B: 게시물 작성시 실행되는 알림 서비스 코드 async createNotifyAlert(id: number) { const data = { alert_place_id: id, alert_type: "NOTIFY" as Type }; const alert = await this.prisma.alert.create({ data: data }); const result = await this.makePostAlertMessage(id); await this.eventsGateway .sendMessage(result) .then((response) => { // console.log("🌠 Notification sent successfully:", response); }) .catch((error) => { console.error("🌠 Error sending notification:", error); // 전송 실패 또는 오류가 발생한 경우에 실행할 로직을 여기에 추가 }); return result; }// fow-be/src/alert/alert.service.ts // C : 댓글 작성시 실행되는 알림 서비스 코드 async createActivityAlert(id: number) { const data = { alert_comment_id: id, alert_type: "ACTIVITY" as Type }; const alert = await this.prisma.alert.create({ data: data }); const result = await this.makeCommentAlertMessage(id); await this.eventsGateway .sendMessage(result) .then((response) => { // console.log("🌠 Notification sent successfully:", response); }) .catch((error) => { console.error("🌠 Error sending notification:", error); }); return result; } // 출력결과# A : 클라이언트에 전송 성공 🌠 sendMessage { sub: 2, user_email: 'shin.yubin18@gmail.com', iat: 1695983169, exp: 1695986769 } # B : 클라이언트에 전송 실패 🌠 sendMessage { place_id: 1, place_name: '코엑스', region_name: '강남구', post_id: 65, post_created_at: 2023-09-29T10:27:28.371Z, post_image_url: 'https://fog-of-war.s3.ap-northeast-2.amazonaws.com/랜드마크/1코엑스.jpeg' } # C : 클라이언트에 전송 실패 🌠 sendMessage { user_nickname: '구글신유빈', user_image_url: 'https://fog-of-war.s3.ap-northeast-2.amazonaws.com/defaultProfile.png', comment_id: 15, comment_text: '우왕', comment_created_at: 2023-09-29T10:52:24.960Z }
-
미해결비전공자를 위한 진짜 입문 올인원 개발 부트캠프
저도 가로 배치가 잘되다가 세로 배치가 되어 질문드립니다.
저도 강의 따라가다가 세로로 갑자기 변환되어서 답변 내용대로 해봤지만 고쳐지지를 않아서 질의 드립니다 아래 코드는 html코드입니다<html> <head> <title>그랩마켓</title> <link href="index.css" type="text/css" rel="stylesheet" /> <body> <div id="header"> <div id="header-area"> <img src="images/images/icons/logo.png"/> </div> </div> <div id="body"> <div id="banner"> <img src="images/images/banners/banner1.png"/> </div> <h1>판매되는 상품들</h1> <div id="product-list"> <div class="product-card"> <img class="product-img" src="images/images/products/basketball1.jpeg"/> <div class="product-contents"> <span class="product-name">농구공 1호</span> <span class="product-price">50000원</span> <div class="product-seller"> <img class="product-avatar" src="images/images/icons/avatar.png"/> <span>그랩</span> </div> </div> </div> </div> <div class="product-card"> <img class="product-img" src="images/images/products/keyboard1.jpg"/> <div class="product-contents"> <span class="product-name">키보드 1호</span> <span class="product-price">30000원</span> <div class="product-seller"> <img class="product-avatar" src="images/images/icons/avatar.png"/> <span>그랩</span> </div> </div> </div> <div class="product-card"></div> <div class="product-card"></div> </div> <div id="footer"></div> </body> </head> </html>아래는 css코드입니다 * { margin: 0; padding: 0; } #header{ height: 64px; display: flex; justify-content: center; border-bottom: 1px solid gray; } #body{ min-height: 100%; width: 1024px; margin: 0 auto; padding-bottom: 24px; } #footer{ height: 200px; background-color: red; } #banner{ height: 300px; background-color: yellow; } #header-area{ width: 1024px; height: 100%; display: flex; align-items: center; } #header-area > img{ width: 128px; height: 36px; } #body > h1{ margin-top: 16px; } #banner > img{ width: 100%; height: 300px; } #product-list{ display: flex; flex-wrap: wrap; margin-top: 12px; flex-direction: row; } .product-card{ width: 180px; height: 300px; margin-right: 12px; margin-bottom:12px; border: 1px solid rgb(230, 230, 230); border-radius: 12px; } .product-img{ width: 100%; height: 210px; } .product-contents{ display: flex; flex-direction: column; padding: 8px; } .product-name{ font-size: 14px; } .product-price{ font-size: 16px; font-weight: 200px; margin-top: 4px; } .product-seller{ display: flex; align-items: center; margin-top: 12px; } .product-avatar{ width: 24px; }바쁘시겠지만 답변 해주시면 감사하겠습니다!+해당 코드 진행 후 개발자 도구 이용해서 보면 flex에 의해 정해지지않은 보라색 칸이 있는데 해당 칸 처리가 힘들어 추가 질문 올립니다!
-
미해결이미지 관리 풀스택(feat. Node.js, React, MongoDB, AWS)
axios 이용해서 백엔드로 이미지 전송 중 새로고침
안녕하세요 강사님.현재 axios 이용해서 백엔드로 이미지 전송하기 강의 수강 중npm i axios로 Axios 모듈 설치 후다음과 같이 코드 작성, npm run start 후 제출 버튼 누를 때 계속하여 새로고침이 됩니다.. ㅠ 원래라면 preventDefault로 새로고침이 되지 않아야 할텐데계속해서 새로고침이 되는 문제입니다. 혹시 문제가 뭘까요? ㅠ
-
미해결탄탄한 백엔드 NestJS, 기초부터 심화까지
res.on('finish')
안녕하세요 강의 잘 듣고 있습니다.res.on('finish', cb); 이벤트를 걸어뒀다고 가정하고 만약 어떤 request에 의한 비즈니스 로직 수행 중적당한 예외처리가 되지 못해서 서버가 죽어버리는 로직을 거쳐 res를 쏘는 부분까지 도달하지 못했다면해당 cb함수는 실행되지 않을거라고 생각했는데 맞을까요?(이렇게 되면.. 어떤 요청에 의해 프로그램이 죽었는지 알기 어려울 것 같다는 생각이 문득 들어서 질문드립니다)