묻고 답해요
129만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
노드 삭제 재설치
그러면 안되지만 잘못 설치했을경우 노드 삭제 재설치 및 버전 업데이트 하는 방법에 대해서 혹시 유튜브에라도 해당 내용이 있을실까요?
-
해결됨[리뉴얼] React로 NodeBird SNS 만들기
어느 순간부터 vs코드에서 저장한 내용이 브라우저에서 적용이 안되고있습니다.
안녕하세요 제로초님어느 순간부터 vs코드에서 저장한 내용이 브라우저에서 적용이 안되고있습니다.새로고침해도 수정한 로직이 적용되지 않은채여서,처음에는 일시적인 에러인가 해서 그냥 ctr + c 로 껐다가다시 npm run dev로 켜서 수정된것 브라우저에서 확인하고 했는데 이게 지속적으로 진행되다보니 어떤 문제가 있는건지도 모르겠고 답답해서 여쭤봅니다.ㅠ노드모듈, .next파일 을 지웠다 다시 설치해보기도 해도 여전히 그대로라 문의 올려봅니다 ㅠ어떤것 때문인지 짐작도 안가서 코드를 못 올리는점 참고부탁드립니다. 제로초님 코딩으 따라가면서 잘됐는데 이부분만 왜 갑자기 이러는지..;;
-
미해결[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
저는왜 렌더링 화면이 다를까요 ?
저는 이 화면으로만 보이고 domain 적는 구간이없는데.. 왜그럴까요 계속 로그인 상태 알람만 발생합니다. <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>API 서버 로그인</title> <style> .input-group label { width: 200px; display: inline-block; } </style> </head> <body> {% if user and user.id %} <span class="user-name">안녕하세요! {{user.nick}}님</span> <a href="/auth/logout"> <button>로그아웃</button> </a> <fieldset> <legend>도메인 등록</legend> <form action="/domain" method="post"> <div> <label for="type-free">무료</label> <input type="radio" id="type-free" name="type" value="free"> <label for="type-premium">프리미엄</label> <input type="radio" id="type-premium" name="type" value="premium"> </div> <div> <label for="host">도메인</label> <input type="text" id="host" name="host" placeholder="ex) zerocho.com"> </div> <button>저장</button> </form> </fieldset> <table> <tr> <th>도메인 주소</th> <th>타입</th> <th>클라이언트 비밀키</th> </tr> {% for domain in domains %} <tr> <td>{{domain.host}}</td> <td>{{domain.type}}</td> <td>{{domain.clientSecret}}</td> </tr> {% endfor %} </table> {% else %} <form action="/auth/login" id="login-form" method="post"> <h2>NodeBird 계정으로 로그인하세요.</h2> <div class="input-group"> <label for="email">이메일</label> <input id="email" type="email" name="email" required autofocus> </div> <div class="input-group"> <label for="password">비밀번호</label> <input id="password" type="password" name="password" required> </div> <div>회원가입은 localhost:8001에서 하세요.</div> <button id="login" type="submit">로그인</button> </form> <script> window.onload = () => { if (new URL(location.href).searchParams.get('error')) { alert(new URL(location.href).searchParams.get('error')); } }; </script> {% endif %} </body> </html> view에 login도 위와 같이 들어가있습니다.const { User, Domain } = require("../models"); const { v4: uuidv4 } = require("uuid"); exports.renderLogin = async (req, res, next) => { try { const user = await User.findOne({ where: { id: res.user?.id || null }, include: { model: Domain } }) res.render("login", { user, domains: user?.Domains }) } catch (err) { console.error(err) next(err); } } exports.createDomain = async (req, res, next) => { try { await Domain.create({ UserId: req.user.id, host: req.body.host, type: req.body.type, client: uuidv4() }) res.redirect("/"); } catch (err) { console.error(err); next(err); } } controller에서도 강의대로 잘 렌더가 들어가있습니다. 그러니 화면이 보이긴하는데 왜 저만안보일까요..- app.js에 passport의 initialize(), session() 함수 선언되어있습니다. - cookie도 있습니다.- db에 user도 있습니다.
-
미해결[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
api호출 제한이 안되는 질문에서 제로초님이 제공해주신 코드중에서의 질문입니다!
해당 질문에서 제로초님이const limiter = rateLimit({ widowMs: 60 * 1000, max: (req, res) => { if (req.user?.type === 'premium') { return 10 } return 1; }, handler(req, res) { res.status(this.statusCode).json({ code: this.statusCode, message: `1분에 ${req.user?.type === 'premium' ? '열' : '한'} 번만 요청 할 수 있습니다...`, }); }, }); exports.apiLimiter = async (req, res, next) => { let user; if (res.locals.decoded) { user = await User.findOne({ where: { id: res.locals.decoded.id } }); } req.user = user; limiter(req, res, next); };이렇게 주셨는데 여기서 limiter을 상수형태로 참조하게끔하면 그럼 다수의 유저가 호출을 하게 될때limiter이 같은 함수를 가르키고있어서 다른 유저가 호출한 api횟수에 영향을 받게 되지않나요? 강의 너무 잘보고있습니다!
-
미해결습관부터 바꿔주는 Node.js & Express 기초
swagger /user/detail/:id 조회시 id로 조회 안됩니다.
스웨거에서/users/detail/:id 조회시 id로 조회가 되지 않습니다. const {id} = req.params;id에 해당 값이 들어오질 않네요.req.params 에id:":id" 이렇게 값이 들어옵니다.id: ':id'} github에서 다운받아서 해도 같은 현상입니다.확인 부탁드립니다.
-
미해결탄탄한 백엔드 NestJS, 기초부터 심화까지
S3에 업로드까지는 성공했는데 사진이 나오지 않습니다.
작성한 코드https://github.com/Parkdev/myfirstnest 업로드 완료 후 결과 링크https://devpark-awsnestcat.s3.ap-southeast-2.amazonaws.com/cat/1713862948347_1.jpeg 업로드 완료까지는 성공하였으나, 업로드 한 사진이 파일이 깨져서 올라가고 있습니다. 어디가 잘못되었는지 잘모르겠네요. 도와주세요.
-
미해결[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
서버 배포 후 api 연동 시에 net::ERR_CONNECTION_REFUSED 에러가 나옵니다
안녕하세요 제로초님! 항상 좋은 강의 올려주셔서 감사합니다 제로초님 강의를 그대로 따라하다가 react로 혼자 프론트를 만들어서 api 연동 웹사이트를 만드는 중입니다. 서버 배포까지 마쳐서 pm2 list 해도 재시작 0회로 잘 올라가 있는 상황입니다! 그런데 프론트에 서버 주소를 입력해서 테스트를 해보니 아래와 같은 에러가 나옵니다. (프론트는 아직 localhost를 사용하고 있습니다) 프론트에서는 아래와 같이 주소를 연동해서 사용했습니다export const url = "http://106.10.34.138"; 강의 때 백엔드에 8002 포트 설정을 해줬어서 :8002를 붙여봤지만 동일한 오류가 나왔습니다 프론트, 서버 둘다 cors 에러가 나올까봐 아래처럼 cors 설정도 해줬습니다//프론트 headers: { "Access-Control-Allow-Origin": "*", },app.use( cors({ origin: "*", credentials: true, }) ); 이제 잘 되는지만 테스트 하면 되는 단계인데 여기서 막혀서 도저히 해결이 안되네요 이런 경우에 어떻게 해결할 수 있는지 알려주시면 감사하겠습니다! 늘 좋은 강의 감사합니다
-
미해결비전공자를 위한 진짜 입문 올인원 개발 부트캠프
CSS 적용 안되는 현상
위와 같이 코드를 작성하였습니다만, body 부분의 css가 적용이 안됩니다.여기서 제가 궁금한 것은 .html 파일 위의 <!DOCTYPE html>을 삭제하면 body값이 100%에 맞게 보여지는데, 왜 이렇게 적용 되는지 잘 모르겠습니다..<!DOCTYPE html>의 태그 같은 경우는 문서 형식을 선언하는것으로 알고있는데..해당 코드의 존재 유무에 따라 CSS 적용이 되다 안되다가 하는지 잘 모르겠습니다.. 답변 주시면 감사드리겠습니다!!
-
미해결
express vercel 배포 500: INTERNAL_SERVER_ERROR
express 서버를 vercel로 배포 하는데 500에러가 뜨는데 왜 뜨는지 어디가 문제인지 모르겠어요... 도움주실수 있으실까요 ㅠㅠ
-
미해결[리뉴얼] React로 NodeBird SNS 만들기
도메인을 연결하고 프론트 도메인으로 접속 로딩시간이 엄청 오래걸립니다.
도메인을 연결하고 프론트 도메인으로 접속 로딩시간이 엄청 오래걸립니다.이런경우는 도대체 뭐때문에 그럴까요? 용량이 커서 그럴까요?백 서버 도메인은 접속이 잘됩니다..vscode에서도 front터미널만 자꾸 렉걸리는 현상이 생겨요 ㅠㅠ
-
해결됨Slack 클론 코딩[백엔드 with NestJS + TypeORM]
socket io 미 연결 문제 (nest & flutter)
안녕하세요! socket관련한 서비스를 진행해보고 싶어서 제로초님의 강의를 들은 수강생입니다.현재 nest & flutter를 이용하고 있는데, flutter에서의 연결 및 다른 tool에서 socket io 연결이 되지 않으며 “외부 사이트로는 접근이 불가능한 오류”가 생겨서 조심스럽게 여쭤봅니다. 현재 로직은 채팅을 생성시, 채팅을 보여주는 리스트가 실시간으로 새로고침이 되는 부분을 작업중입니다.하지만, postman, httpie, hoppscotch의 부분에서 연결이 되지 않는 문제가 발생합니다.많은 방법을 찾아봤지만, 터미널에서 socket io cli를 통해서 로그는 볼 수 있지만, 다른 tool에서는 이용이 불가능한 방법에 대해서 알고 싶어서 질문드립니다!Socket io를 통해서 local, dev서버 연결 완료 하지만 postman의 socket io기능을 통해서 테스트를 진행하려고 할 때,postman으로 연결local에서는 문제가 없이 연길이 되지만, dev서버에서는 이러한 에러가 발생합니다. 또한 flutter 앱에서 연결을 하려면 다음과 같은 에러가 발생합니다.오류 메시지 "WebSocketException: Connection to 'http://~~~~.com:81/socket.io/?EIO=4&transport=websocket#' was not upgraded to websocket"는 클라이언트가 WebSocket 연결을 시도하였으나, 서버가 해당 연결을 WebSocket 프로토콜로 업그레이드하지 않았다는 것을 의미합니다. 이는 여러 가지 원인에 의해 발생할 수 있습니다: upgrade가 되지 않았다고 나와서 ,ngnix의 socket 부분에서 upgrade부분도 잘 넣어줬는데, 오류가 해결되지 않아서... 고민 끝에 질문 올립니다.Ngnix 설정부터 2주정도 시간을 들였지만, 해결이 되지 않아서…여쭤봅니다.방화벽도 해제가 되어 있는데 연결이 안되고 있습니다..다음은 nest에서 작성한 코드 입니다![chat.gateway.ts]import { WebSocketGateway, WebSocketServer, SubscribeMessage, OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit, ConnectedSocket, MessageBody, } from '@nestjs/websockets'; import { Server, Socket } from 'socket.io'; @WebSocketGateway() export class ChatGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect { @WebSocketServer() server: Server; afterInit(server: Server) { console.log('WebSocket initialized'); } handleConnection(client: Socket) { console.log(`Client connected: ${client.id}`); // 수정: client 객체 직접 출력 대신 id 출력 } handleDisconnect(client: Socket) { console.log(`Client disconnected: ${client.id}`); } @SubscribeMessage('sendMessage') handleMessage( @ConnectedSocket() client: Socket, @MessageBody() data: { message: string } ): void { console.log(`Received message from ${client.id}: ${data.message}`); this.server.emit('newMessage', data); // 모든 클라이언트에게 메시지 전송 console.log(`Received message: ${data.message}`); } } [main.ts]import { ConfigService } from '@nestjs/config'; import { NestFactory } from '@nestjs/core'; import { NestExpressApplication } from '@nestjs/platform-express'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { join } from 'path'; import { AppModule } from './app.module'; import { HttpExceptionFilter } from './common/exceptions/http-exception.filter'; import { SuccessInterceptor } from './common/interceptors/success.interceptor'; import { IoAdapter } from '@nestjs/platform-socket.io'; import { CustomIoAdapter } from './adapters/custom-io.adapter'; async function bootstrap() { const app = await NestFactory.create<NestExpressApplication>(AppModule); app.useWebSocketAdapter(new CustomIoAdapter(app)); const configService = app.get(ConfigService); const port = configService.get('server.port'); const mongoUrl = configService.get('DB.MONGO_URL'); console.log('MongoDB URL:', mongoUrl); app.enableCors({ origin: true, credentials: true, }); app.useStaticAssets(join(__dirname, '..', 'client'), { prefix: '/api/v1/client', }); app.useGlobalInterceptors(new SuccessInterceptor()); app.useGlobalFilters(new HttpExceptionFilter()); app.setGlobalPrefix('api/v1'); const swagger_options = new DocumentBuilder() .setTitle('Nyam-Docs') .setDescription('API description') .setVersion('2.0.1') .addApiKey( { type: 'apiKey', name: 'x-token', in: 'header', description: 'Enter token', }, 'x-token', ) .addApiKey( { type: 'apiKey', name: 'x-type', in: 'header', description: 'Enter type', }, 'x-type', ) .build(); const document = SwaggerModule.createDocument(app, swagger_options); SwaggerModule.setup('api-docs', app, document); await app.listen(port, '0.0.0.0'); console.log(`Application Listening on Port : ${port}`); } bootstrap();다음은 custom한 io입니다[custom.io.adpter.ts]import { IoAdapter } from '@nestjs/platform-socket.io'; import { INestApplication, Injectable } from '@nestjs/common'; import { ServerOptions } from 'socket.io'; @Injectable() export class CustomIoAdapter extends IoAdapter { constructor(app: INestApplication) { super(app); } createIOServer(port: number, options?: ServerOptions): any { const serverOptions: ServerOptions = { ...options, cors: { origin: '*', // 모든 도메인에서 접근 허용 methods: ['GET', 'POST', 'PUT', 'DELETE'], credentials: true }, transports: ['websocket', 'polling'], //pooling 없으면 연결 안 됨(socket) allowEIO3: true // Engine.IO 3.x 버전 클라이언트 허용 }; return super.createIOServer(port, serverOptions); } } 혹시 해결방법을 아시거나, 도움을 주실만한 정보가 있으시다면 알려주시면 정말 감사하겠습니다!
-
미해결비전공자를 위한 진짜 입문 올인원 개발 부트캠프
map foreach 매개변수 이름은 product, index아니여도 되네요
그냥 첫번째 매개변수가 대상이고 두번째 매개변수는 index취급하는건가요?
-
미해결비전공자를 위한 진짜 입문 올인원 개발 부트캠프
postman으로 만든 주소는 만든사람 본인만 들어가지는건가요
다른 사람은 못보는걸까요
-
미해결Do it! Node.js 프로그래밍 입문
8:34초 간단한 질문있습니다
hashedPassword 부분에서 10이 의미하는 것은 무엇인가요??
-
미해결[리뉴얼] React로 NodeBird SNS 만들기
reducer설정 중 user 초기값이 undefined로 나오는 에러
안녕하십니까 형님진행하다 보니 궁금한게 생겨서 여쭤보려고 합니다. reducer설정 중 초기값이 undefined로 들어오는 에러가 놔왔었는데욥error - Error: The slice reducer for key "user" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined. 에러 났던 부분운 default: state 이 부분이고 코드 보고 아래처럼 수정하니 잘 동작했습니다. export const initialState = { isLoggedIn: false, user: null, signUpData: {}, loginData: {}, } const reducer = (state=initialState, action) => { switch(action.type) { default: { return { ...state } } } }default: state vs default: { return {...state}}문법적으로 똑같은 내용이 아닌지...어떤 차이가 있는지를 모르겠어서 질문드립니다!
-
미해결비전공자를 위한 진짜 입문 올인원 개발 부트캠프
display flex 및 link가 제대로 작동 안합니다...ㅠ
안녕하세요! 두 가지 질문이 있어서 글 남깁니다. display flex가 특정 id에 적용이 안됩니다 ㅠㅠapp.js에서 id=header인 부분에 css를 적용시켰는데 딱 header 부분만 적용이 안됩니다. 코드는 아래와 같습니다. app.js 코드import logo from './logo.svg'; import './App.css'; import MainPageComponent from "./main/index.js" import React, { Component } from 'react'; import {Link, Switch, Route, useHistory} from 'react-router-dom' import UploadPage from './upload/index.js'; import ProductPage from './product/index.js'; import { Button } from 'antd'; import {DownloadOutlined} from '@ant-design/icons' function App() { const history = useHistory(); return ( <div> <div id="header"> <div id="header-area"> <Link to="/"> <img src="/images/icons/logo.png" /> </Link> <Button size="large" onClick={function(){ history.push('/upload'); }} icon={<DownloadOutlined />} > 상품 업로드 </Button> </div> </div> <div id="body"> <Switch> <Route exact={true} path="/"> <MainPageComponent /> </Route> <Route exact={true} path="/products/:id"> <ProductPage /> </Route> <Route exact={true} path="/upload"> <UploadPage /> </Route> </Switch> </div> <div id="footer"></div> </div> ); } export default App; app.css* { margin: 0; padding: 0; line-height: normal; } html, body, #root, #root > div { height: 100%; }; #header { height: 64px; /*가운데 정렬하는 방법*/ display: flex; justify-content: center; border-bottom: 1px solid gray; } #header-area { width: 1024px; height: 100%; display: flex; align-items: center; justify-content: space-between; } #header-area img { width: 128px; height: 36px; } #body { height: 100vh; width: 1024px; margin: 0 auto; /*가운데 정렬하는 방법 중 하나*/ padding: 24px; } #footer { height: 200px; background-color: rgb(230,230,230); }이렇게 했을 때 아래와 같이 header만 적용이 안됩니다...(header-area는 css가 잘 적용이 되네요) Link 제대로 작동 안됨Link 태그를 통해 상품 상세페이지로 넘어가는 코드를 구현했는데 잘 안되는 부분이 있습니다 ㅠㅠ 원래라면 상품 카드를 눌렀을 때 자동으로 상품 상세페이지로 넘어가면서 해당 페이지 내용이 나타나야하는데 저는 카드를 누르면 url 주소만 바뀌고 제가 수동으로 새로고침을 해야 해당 페이지로 넘어갑니다...(그랩마켓 로고를 눌렀을 때 메인페이지로 돌아가는 것도 마찬가지입니다) 위 코드에서 잘못된 부분이 어떤거길래 이렇게 되는걸까요...? 감사합니다!
-
미해결Slack 클론 코딩[백엔드 with NestJS + TypeORM]
no elements in sequence 에러 관해서 질문이 있습니다.
안녕하세요. nestjs를 사용해서 백엔드를 구성하고 있는데 RxJS의 no elements in sequence라는 에러에 대해서 질문이 있습니다.const findObject = await this.respository.findOne({ where: { data } }) if (findObject) { throw new HttpException("중복 접수 되었습니다.", HttpStatus.CONFLICT); }DB에서 찾은 객체가 있을 경우, Exception으로 에러를 내면서 종료를 시키는 로직을 생각하고 작성을 했습니다. 그런데 정작 오류는 no elements in sequence 와 함께 500 응답코드가 반환되는데요.반환 할 값이 없을경우 나는 에러로 알고있는데, throw만 하고 리턴하는 값이 없어서 발생 하는 것 같습니다.그리고 발생하는 두 오류 중, no elements in sequence가 먼저 반환되어 종료되기때문에 409에러가 묻히는 것으로 추측을 하고있는데 409에러를 먼저 내는 방법은 없을까요?
-
미해결Do it! Node.js 프로그래밍 입문
delete 부분에서 13:28 질문있습니다
13:28 delete 부분에서 강의를 보면 const contact = await Contact.findById(id);를 통해서 정보를 contact 변수에 할당하고막상 deleteOne함수는 Contact에서 합니다 contact에서 deleteOne을 사용하면 안되나요?Contact에서와 contact에서 deleteOne을 사용했을 때의 차이가 궁금하고 Contact에서 delete를 할 것이면 왜 굳이 새로운 변수에 할당을 해주는 것인지 궁금합니다
-
미해결Do it! Node.js 프로그래밍 입문
에러 도와주세요
6:26 기준 똑같이 따라했는데 TypeError: Cannot use 'in' operator to search for 'pluralization' in undefined at Mongoose._model (/Users/leooh/Desktop/doit-node-main/myContacts/node_modules/mongoose/lib/mongoose.js:612:43) at Mongoose.model (/Users/leooh/Desktop/doit-node-main/myContacts/node_modules/mongoose/lib/mongoose.js:581:27) at Object.<anonymous> (/Users/leooh/Desktop/doit-node-main/myContacts/models/contactModel.js:20:26) at Module._compile (node:internal/modules/cjs/loader:1376:14) at Module._extensions..js (node:internal/modules/cjs/loader:1435:10) at Module.load (node:internal/modules/cjs/loader:1207:32) at Module._load (node:internal/modules/cjs/loader:1023:12) at Module.require (node:internal/modules/cjs/loader:1235:19) at require (node:internal/modules/helpers:176:18) at Object.<anonymous> (/Users/leooh/Desktop/doit-node-main/myContacts/controllers/contactController.js:2:17) 오류가 나옵니다 무엇이 문제일까요??
-
미해결Do it! Node.js 프로그래밍 입문
status 작성 이유가 궁금합니다
controller1을 참고하라고 하셔서 혼자 코드를 작성한 후 코드를 봤는데 원래는 없는 status함수가 추가 되어 있습니다 서칭을 해본결과 status(200)은 request가 완료된 것을 알리는 상태 코드라고 하는데 그 목적으로 사용한 것인가요? status 함수 없이 작성해도 상관없던데 추가하신 이유가 궁금합니다!