inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

묻고 답해요

172만명의 커뮤니티!! 함께 토론해봐요.

카카오 로그인 질문드립니다!

미해결

[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지

안녕하세요!! 제가 지금 Next.js와 Node.js를 활용해서 중고거래 사이트를 프론트와 백 둘다 구현을 하려고 하는데 프론트(NextAuth)에서 API 를 받아와 카카오 로그인을 구현하면, 백에서는 카카오 로그인에대한 구현을 할 필요가 없는건가요? 또, 프론트 나 백 둘중 어느곳에서 카카오 로그인을 구현해야 효율적인지 궁금합니다!

  • node.js
  • mysql
  • mongodb
  • express
  • typescript
  • socket.io
  • jwt
rlaghdwns777 댓글 1 좋아요 0 조회수 295

pd.get_dummies(train[cols])와 (train, columns=cols) 차이가 궁금합니다.

해결됨

[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)

원핫 인코딩 코드에서 괄호 안에 [cols]를 쓸 때와 columns=cols를 쓸 때의 차이가 궁금합니다. 3-4 Feature engineering에서와 3-6 Regression에서 작성법이 달라서요. 3-6 Regression에서는 train[cols]로 썼더니 에러가 나네요ㅠ # 3-4 Feature engineering c_train[col] = le.fit_transform(c_train[col]) c_test[col] = le.transform(c_test[col]) # 3-6 Regression train = pd.get_dummies(train, columns=cols) test = pd.get_dummies(test, columns=cols)

  • python
  • 머신러닝
  • 빅데이터
  • pandas
  • 빅데이터분석기사
kimx2725 댓글 1 좋아요 0 조회수 446

11.3 통합테스트 중 TypeError: model.initiate is not a function

해결됨

[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지

질문할까 고민하다가 용기내어 질문드려봅니다..! 11장 통합테스트 중 나타난 에러입니다. npm test 를 입력하면 나오는 에러입니다. > nodebird@0.0.1 test > jest PASS models/user.test.js PASS services/user.test.js PASS middlewares/index.test.js FAIL routes/auth.test.js ● Test suite failed to run TypeError: model.initiate is not a function 22 | console.log(file, model.name); 23 | db[model.name] = model; > 24 | model.initiate(sequelize); | ^ 25 | }); 26 | 27 | Object.keys(db).forEach(modelName => { // associate 호출 at initiate (models/index.js:24:11) at Array.forEach (<anonymous>) at Object.forEach (models/index.js:20:4) at Object.require (routes/auth.test.js:2:23) Test Suites: 1 failed, 3 passed, 4 total Tests: 9 passed, 9 total Snapshots: 0 total Time: 0.725 s, estimated 1 s 현재 에러는 model.initiate가 함수화가 되지 않았다고 나타는거 같습니다. model.initiate가 존재하는 index.js입니다. const Sequelize = require('sequelize'); const fs = require('fs'); const path = require('path'); 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.sequelize = sequelize; const basename = path.basename(__filename); fs .readdirSync(__dirname) .filter(file => { return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'); }) .forEach(file => { const model = require(path.join(__dirname, file)); console.log(file, model.name); db[model.name] = model; model.initiate(sequelize); // 오류 발생시점 }); Object.keys(db).forEach(modelName => { if (db[modelName].associate) { db[modelName].associate(db); } }); module.exports = db; 11.3 강의를 보는 중이며 auth.test.js 코드를 작성중입니다 작성중인 auth.test.js는 아래와 같습니다. const app = require('../app'); const request = require('supertest'); const { sequelize } = require('../models'); beforeAll(async () => { await sequelize.sync() }) beforEach(() => { }); describe('POST /join', () => { test('로그인 안 했으면 가입', (done) => { request(app).post('/auth/join') .send({ email: 'choibo@naver.com', nick: 'bobobo', password: 'choibo11' }) .expect('Location', '/') .expect(302, done) }) }) describe('POST /login', () =>{ test('로그인 수행', (done) => { request(app).post('/auth/login') .send({ email: 'choibo@naver.com', password: 'choibo11' }) .expect('Location', '/') .expect(302, done) }) }); afterEach(() => {}); aftereAll(() => { }); 이부분에서 에러가 발생한다고 나타나있습니다. const { sequelize } = require('../models');

  • node.js
  • mysql
  • mongodb
  • express
  • typescript
  • socket.io
  • jwt
승현 댓글 2 좋아요 0 조회수 708

S3 버킷 만들 때 암호화 유형

미해결

[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지

버킷 만들때 강의 와 달리 처음부터 저렇게 선택되어있던데 그냥 원래 선택되었던거 유지하면서 만들면 되나요?

  • node.js
  • mysql
  • mongodb
  • express
  • typescript
  • socket.io
  • jwt
김명재 댓글 1 좋아요 0 조회수 262

pm2 error

미해결

[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지

const express = require("express"); const cookieParser = require("cookie-parser"); const morgan = require("morgan"); const session = require("express-session"); const router = express.Router(); const path = require("path"); const dotenv = require("dotenv"); const passport = require("passport"); const app = express(); const passportConfig = require("./passport"); const redis = require("redis"); const RedisStore = require("connect-redis").default; dotenv.config(); const redisClient = redis.createClient({ url: `redis://${process.env.REDIS_HOST}:${process.env.REDIS_PORT}`, password: process.env.REDIS_PASSWORD, legacyMode: false, }); redisClient.connect().catch(console.error); const authRouter = require("./routes/auth"); const pageRouter = require("./routes/page"); const postRouter = require("./routes/post"); const userRouter = require("./routes/user"); const commentRouter = require("./routes/comment"); const updateRouter = require("./routes/update"); const deleteRouter = require("./routes/delete"); const helmet = require("helmet"); const hpp = require("hpp"); const { sequelize } = require("./models"); const logger = require("./logger"); passportConfig(); app.set("port", process.env.PORT || 8005); sequelize .sync({ force: false }) .then(() => { console.log("데이터베이스 연결 성공"); }) .catch((err) => { console.error(err); }); if (process.env.NODE_ENV === "production") { app.use( helmet({ contentSecurityPolicy: false, crossOriginEmbedderPolicy: false, crossOriginResourcePolicy: false, crossOriginOpenerPolicy: false, originAgentCluster: false, }) ); app.use(hpp()); app.use(morgan("combined")); } else { app.use(morgan("dev")); } app.use(express.json({ limit: "10mb" })); var cors = require("cors"); const { deepStrictEqual } = require("assert"); app.use(cors()); app.use("/img", express.static(path.join(__dirname, "uploads"))); app.use("/profileImg", express.static(path.join(__dirname, "profileImg"))); app.use(express.json()); app.use(express.urlencoded({ limit: "10mb", extended: false })); app.use(cookieParser(process.env.COOKIE_SECRET)); const sessionOption = { resave: false, saveUninitialized: false, secret: process.env.COOKIE_SECRET, cookie: { httpOnly: true, secure: false, }, store: new RedisStore({ client: redisClient }), }; if (process.env.NODE_ENV === "production") { sessionOption.proxy = true; } app.use(session(sessionOption)); app.use(passport.initialize()); app.use(passport.session()); app.use(express.static(path.join(__dirname, "prototype-client/build"))); app.get("/", (req, res) => { res.sendFile(path.join(__dirname, "prototype-client/build/index.html")); }); app.use("/page", pageRouter); app.use("/auth", authRouter); app.use("/post", postRouter); app.use("/user", userRouter); app.use("/comment", commentRouter); app.use("/update", updateRouter); app.use("/delete", deleteRouter); //react에서 react-router-dom으로 다룰 수 있게 app.get("*", function (req, res) { res.sendFile(path.join(__dirname, "/prototype-client/build/index.html")); }); //에러 처리 담당 app.use((req, res, next) => { const error = new Error(`${(req, method)} ${req.url} 라우터가 없습니다.`); error.status = 404; logger.info("hello"); logger.error(error.message); next(error); }); app.use((err, req, res, next) => { console.error(err); res.locals.message = err.message; res.locals.erorr = process.env.NODE_ENV !== "production" ? err : {}; res.status(err.status || 500); res.render("error"); }); module.exports = app; 이렇게 코드를 실행하면 sudo pm2 monit의 server log에 2가지 에러가 나옵니다. server > [Error: ENOENT: no such file or directory, stat │ ││ server > errno: -2, │ ││ server > code: 'ENOENT', │ ││ server > syscall: 'stat', │ ││ server > path: '/home/bitnami/Whats-up/prototype-client/bu │ │ ││ server > expose: false, │ ││ server > statusCode: 404, │ ││ server > status: 404 │ ││ server > } 에러 메시지를 봤을때 해당 경로에 대한 파일을 찾을 수 없다고 하는데 ls를 입력했을때 잘 있는걸 확인 할 수 있는데 왜 이런 에러가 발생하는지 모르겠습니다.. 2번쨰는 server > Error: No default engine was specified and no ││ server > at new View (/home/bitnami/Whats-up/node_module │ ││ server > at Function.render (/home/bitnami/Whats-up/node │ ││ server > at ServerResponse.render (/home/bitnami/Whats-u │ ││ server > at /home/bitnami/Whats-up/app.js:127:7 │ ││ server > at Layer.handle_error (/home/bitnami/Whats-up/n │ ││ server > at trim_prefix (/home/bitnami/Whats-up/node_mod │ ││ server > at /home/bitnami/Whats-up/node_modules/express/ ││ server > at Function.process_params (/home/bitnami/Whats 이런 에러가 발생합니다. 에러 메세지를 봤을떄는 view engine관련된 에러같은데 react랑 express연동할때는 따로 view engine 설정을 주지 않고 express.static으로 리액트 코드를 전달하면 되는거 아닌가요?

  • node.js
  • mysql
  • mongodb
  • express
  • typescript
  • socket.io
  • jwt
김명재 댓글 2 좋아요 0 조회수 621

인코딩과 컬럼선택기준

해결됨

[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)

인코딩을 할때 선생님이 어쩔때는 원핫인코딩을 하시고 어쩔때는 레이블인코딩을 하시던데 그 인코딩을 정하시는 기준을 잘 모르겠습니다! 인코딩을 정하실때 그 경우에 대해서 자세히 알려주시면 감사하겠습니다 그리고 인코딩을 할때 컬럼도 몇개 정하셔서 하시던데 그 컬럼고르는 기준도 잘 모르겠습니다 그 기준에 대해서도 선택하는 방법을 알려주시면 감사하겠습니다 ㅠㅠ

  • python
  • 머신러닝
  • 빅데이터
  • pandas
  • 빅데이터분석기사
jms717958 댓글 1 좋아요 0 조회수 373

AWS 설정 후 실행했을때 사이트에 연결할 수 없음이 뜹니다

미해결

[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지

저는 지금 단순 html페이지 대신 react와 함께 nodebird 프로젝트를 하고 있는데요. 지금 aws설정도 다 마치고 pm2를 실행하고 sudo pm2 list를 해봐도 오류 없이 잘 실행됩니다. 그래서 크롬 주소창에 ip를 입력하면 사이트에 연결할 수 없다고 합니다.. 직접적으로 에러가 뜨는 것도 아니여서 어디가 문제인지 잘 모르겠습니다.. github: https://github.com/AUDWO/Whats-up/blob/main/app.js (prototype-client가 리액트로 만든 페이지 입니다)

  • node.js
  • mysql
  • mongodb
  • express
  • typescript
  • socket.io
  • jwt
김명재 댓글 1 좋아요 0 조회수 691

작업형2에서 언제는 분류모델을 써야하고 언제는 회귀모델을 써야할까요?!

해결됨

[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)

보통 작업형2에서는 예측값을 물어보는 문제가 나오던데요. 문제가 나올때 어느문제는 분류모델을, 어느문제는 회귀모델을 사용해야하는지 궁금합니다. 지금까지 강의+기출문제를 보면서는 분류/회귀를 결정하는 부분이 평가 모델을 통해 진행된다는 느낌을 받았는데요. 1) roc_auc_score, accuracy_score 이 평가모델로 쓰일 경우, 분류형 모델 사용(Classifier) 2) rmse, mean_squared_error 이 평가모델로 쓰일 경우, 회귀모델 사용(Regressor) 이렇게 생각하면서 작업형2를 접근하는게 맞는지 궁금합니다.

  • python
  • 머신러닝
  • 빅데이터
  • pandas
  • 빅데이터분석기사
hello4298 댓글 1 좋아요 0 조회수 383

unread Count 같은 경우 실무에선는 DB에 마지막 일자를 기록하나요?

해결됨

Slack 클론 코딩[실시간 채팅 with React]

강의에서 localStorage 를 이용하여 접속시간 or 마지막 불러온 일자를 저장하고 그 local 값을 unreads 에 after 파람으로 전송하여 읽지않은 메시지를 카운트 햇는데 해당 방식은 다른 아이디로 로그인 시 같은 local 데이터를 활용하기도 하고 다른 기기에 접속시 해당값은 날라가게 될텐데 이는 에러사항으로 이어질 것으로 예상됩니다. 마지막 일자를 활용하게 된다면 이 값은 db에 저장되야 할걸로 생각이 되는데 맞을까요?

  • react
  • 웹팩
  • typescript
  • socket.io
  • babel
  • 클론코딩
최석우 댓글 1 좋아요 0 조회수 270

내부디비를 세부적으로 쓰고싶은데...

해결됨

Slack 클론 코딩[실시간 채팅 with React]

sleact 서비스에 내부스토리지 (web스토리지,indexedDB) 를 좀더 체계적으로 써야될것같은데 zustand 같은 상태관리 라이브러리에 내부스토리지를 연결하는게 좋을까요? 아니면 swr 같은데다 연결하는게 좋을까요? 아니면 내부스토리 접근하는 코드 따로 빼놓고 데이터 가져와서 state 에 관리하는게 나을까요?

  • react
  • 웹팩
  • typescript
  • socket.io
  • babel
  • 클론코딩
쵸잉 댓글 1 좋아요 1 조회수 294

onScroll 스크롤 위치 유지가 안됩니다 ㅠ

미해결

Slack 클론 코딩[실시간 채팅 with React]

import Chat from '@components/Chat'; import { ChatZone, Section, StickyHeader } from '@components/ChatList/style'; import { IChat, IDM } from '@typings/db'; import React, { FC, RefObject, VFC, forwardRef, useCallback, useRef } from 'react'; import { Scrollbars } from 'react-custom-scrollbars'; interface Props { scrollRef: RefObject<Scrollbars>; chatSections: { [key: string]: IDM[] }; setSize: (f: (index: number) => number) => Promise<IDM[][] | undefined>; isEmpty: boolean; isReachingEnd: boolean; } const ChatList: VFC<Props> = (({ chatSections, setSize, isEmpty, scrollRef, isReachingEnd}) => { const onScroll = useCallback((values) => { // 끝에 도달하면 불러오지 않기 if(values.scrollTop === 0 && !isReachingEnd){ console.log('가장 위'); setSize((prevSize) => prevSize + 1).then(()=>{ // 스크롤 위치 유지 if(scrollRef?.current){ scrollRef.current?.scrollTop(scrollRef.current?.getScrollHeight() - values.scrollHeight); } }); } }, []); return ( <ChatZone> <Scrollbars autoHide ref={scrollRef} onScrollFrame={onScroll}> {Object.entries(chatSections).map(([date, chats]) => { return ( <Section className={`section-${date}`} key={date}> <StickyHeader> <button>{date}</button> </StickyHeader> {chats.map((chat) => ( <Chat key={chat.id} data={chat} /> ))} </Section> ); })} </Scrollbars> </ChatZone> ); }); export default ChatList; 이쪽 코드는 문제가 없는것같은데 희한하게 위치가 유지가 되지않고 원래처럼 쭉 올라가버립니다.. ref쪽이 문제인가요..? 혹시몰라 DirectMessage 컴포넌트도 아래에 첨부하겠습니다. import React, { useCallback, useEffect, useRef } from 'react'; import gravator from 'gravatar'; import useSWR, { mutate } from 'swr'; // swr 인피니티스크롤링 전용 메서드 import useSWRInfinite from 'swr/infinite'; import { IDM, IUser } from '@typings/db'; import fetcher from '@utils/fetcher'; import { useParams } from 'react-router'; import ChatBox from '@components/ChatBox'; import { Container, Header } from '@pages/DirectMessage/style'; import ChatList from '@components/ChatList'; import useInput from '@hooks/useInput'; import axios from 'axios'; import makeSection from '@utils/makeSection'; import Scrollbars from 'react-custom-scrollbars'; const DirectMessage = () => { const { workspace, id } = useParams<{ workspace: string; id: string }>(); const { data: userData } = useSWR(`http://localhost:3095/api/workspaces/${workspace}/users/${id}`, fetcher); // 내정보 const { data: myData } = useSWR(`http://localhost:3095/api/users`, fetcher); const [chat, onChangeChat, setChat] = useInput(''); // 과거 채팅리스트에서 채팅을 치면 최신목록으로 바로 스크롤을 내려줄려면 ref를 // 이 컴포넌트에서 props로 내려줘야하기 때문에 forwardRef를 사용해서 props로 넘겨준다 // 💡 HTML 엘리먼트가 아닌 React 컴포넌트에서 ref prop을 사용하려면 React에서 제공하는 forwardRef()라는 함수를 사용해야 합니다 const scrollbarRef = useRef<Scrollbars>(null); // 채팅 받아오는곳 (setSize : 페이지수를 바꿔줌) // useSWRInfinite를 쓰면 [{id:1},{id:2},{id:3},{id:4}] 1차원배열이 [[{id:1},{id:2}],[{id:3},{id:4}]] 2차원배열이 된다. const { data: chatData, mutate: mutateChat, setSize, } = useSWRInfinite<IDM[]>( (index) => `http://localhost:3095/api/workspaces/${workspace}/dms/${id}/chats?perPage=20&page=${index + 1}`, fetcher, ); // 데이터 40 개중에 20개씩 사져오면 첫번째페이지부터 20 + 20 + 0 세번째 페이지 0 이되면 isEmpty, isReachingEnd는 true가 됨 // 반대의 상황에서 데이터가 45개면 20 + 20 + 5 isEmpty는 0이 아니라서 false isReachingEnd는 여전히 데이터 가져옴 const isEmpty = chatData?.[0]?.length === 0; const isReachingEnd = isEmpty || (chatData && chatData[chatData.length - 1]?.length < 20) || false; const onSubmitForm = useCallback( (e) => { e.preventDefault(); if (chat?.trim() && chatData) { const savedChat = chat; // 💡 옵티미스틱 UI // 서버쪽에 다녀오지 않아도 성공해서 데이터가 있는거처럼 보이게 미리 만듦 mutateChat((prevChatData) => { // infinite 스크롤링은 2차원 배열이다. prevChatData?.[0].unshift({ // unshift : 앞쪽에 추가 id: (chatData[0][0]?.id || 0) + 1, content: savedChat, SenderId: myData.id, Sender: myData, ReceiverId: userData.id, Receiver: userData, createdAt : new Date(), }); return prevChatData; },false) // 옵티미스틱 UI 할땐 이부분이 항상 false .then(()=>{ setChat(''); // 버튼클릭 시 기존 채팅지우기 scrollbarRef.current?.scrollToBottom(); // 채팅 첬을때 맨 아래로 }) axios .post( `http://localhost:3095/api/workspaces/${workspace}/dms/${id}/chats`, { content: chat, }, { withCredentials: true, }, ) .then(() => { mutateChat(); // SWR에서 데이터를 다시 불러와서 캐시를 갱신하는 역할을 합니다. }) .catch(() => { console.error; }); } }, [chat, chatData, myData, userData, workspace, id], ); // (채팅이 최신것을 아래에 두기 위함) = 기존것 데이터를두고 새 데이터를 뒤집어서 출력 / flat() 배열을 1차원 배열로 만들어줌 const chatSections = makeSection(chatData ? [...chatData].flat().reverse() : []); // 로딩 시 스크롤바 제일 아래로 useEffect(()=>{ if(chatData?.length === 1){ // 채팅 데이터가 있어서 불러온 경우 scrollbarRef.current?.scrollToBottom(); // 가장 아래쪽으로 내려줌 } },[chatData]) // 로딩 if (!userData || !myData) { return null; } return ( <Container> <Header> <img src={gravator.url(userData.email, { s: '24px', d: 'retro' })} alt={userData.nickname}></img> <span>{userData.nickname}</span> </Header> {/* 컴포넌트 위치를 미리 지정해도 좋다. */} {/* 전역 상태관리 라이브러리를 사용해도 컴포넌트상황에따라 props 로 넘겨줌*/} <ChatList scrollRef={scrollbarRef} chatSections={chatSections} setSize={setSize} isEmpty={isEmpty} isReachingEnd={isReachingEnd} /> <ChatBox chat={chat} onChangeChat={onChangeChat} onSubmitForm={onSubmitForm} /> </Container> ); }; export default DirectMessage;

  • react
  • 웹팩
  • typescript
  • socket.io
  • babel
  • 클론코딩
복실묘 댓글 2 좋아요 0 조회수 528

작업형2 모의문제3

해결됨

[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)

학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! 질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요 먼저 유사한 질문이 있었는지 검색해보세요 안녕하세요 선생님, 질문은 3가지 입니다. 1) 저는 문제를 딱 접했을때 분류모형을 써야할지, 예측모형을 써야할지 판가름을 정확하게 못하는 것 같습니다. 쉽게 판별하는 방법이 있을까요? 2) 이 문제의 경우 target인 output 컬럼을 train.head() 로 보면 0과 1로 구분되어있어서, 0 또는 1로 분류하는(분류모형) 것인가 생각했다가도 문제 맨위에서 참조해주는 예시에서 id,output 41,0.633 28,0.123 222,0.355 를 보면 output이 확률값으로 되어있어서 회귀모형을 사용해야하는 것인가? 라고 헷갈리곤합니다. 어디서 개념을 잡지 못하는 것일까요 3) 최종 예측을 할때 pd.DataFrame({'id':test_id, 'output':pred_proba[:,1]}).to_csv("00000.csv", index=False) output에 pred_proba 를 쓰셨는데 참조예시에서 확률값을 OUTPUT에 담았기 때문에 pred_proba를 사용한 것일까요? 그렇다면 output에 pred 를 담는 경우는 어떤 경우인지요?

  • python
  • 머신러닝
  • 빅데이터
  • pandas
  • 빅데이터분석기사
댓글 1 좋아요 0 조회수 282

서버 실패시, 패스포트 로그인 실패시 통합테스트 방법

미해결

[개정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를 작성하라고 하신 말씀에 이 부분은 통합테스트로 코드를 짤 수 있나 의문이 들어서요! 감사합니다

  • node.js
  • mysql
  • mongodb
  • express
  • typescript
  • socket.io
  • jwt
kyh_0625 댓글 2 좋아요 1 조회수 422

7.5 시퀄라이즈 사용하기 에러

미해결

[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지

7.5 시퀄라이즈 사용하기 강좌 부분입니다.피피티와 동일하게 작성했는데 sync에러가 자꾸 뜹니다. 어떻게 고쳐야할지 모르겠습니다. app.js const 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.js const 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.js C:\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=PUKOWrOuC0c 0. 숫자 0부터 시작한 이유는 1보다 더 중요한 것이기 때문입니다. 에러가 났을 때 해결을 하는 게 중요한 게 아닙니다. 왜 여러분은 해결을 못 하고 저는 해결을 하는지, 어디서 힌트를 얻은 것이고 어떻게 해결한 건지 그걸 알아가셔야 합니다. 그렇지 못한 질문은 무의미한 질문입니다. 1. 에러 메시지를 올리기 전에 반드시 스스로 번역을 해야 합니다. 번역기 요즘 잘 되어 있습니다. 에러 메시지가 에러 해결 단서의 90%를 차지합니다. 한글로 번역만 해도 대부분 풀립니다. 그냥 에러메시지를 올리고(심지어 안 올리는 분도 있습니다. 저는 독심술사가 아닙니다) 해결해달라고 하시면 아무런 도움이 안 됩니다. 2. 에러 메시지를 잘라서 올리지 않아야 합니다. 입문자일수록 에러메시지에서 어떤 부분이 가장 중요한 부분인지 모르실 겁니다. 그러니 통째로 올리셔야 합니다. 3. 코드도 같이 올려주세요. 다만 코드 전체를 다 올리거나, 깃헙 주소만 띡 던지지는 마세요. 여러분이 "가장" 의심스럽다고 생각하는 코드를 올려주세요. 4. 이 강좌를 바탕으로 여러분이 응용을 해보다가 막히는 부분, 여러 개의 선택지 중에서 조언이 필요한 부분, 제 경험이 궁금한 부분에 대한 질문은 대환영입니다. 다만 여러분의 회사 일은 질문하지 마세요. 5. 강좌 하나 끝날 때마다 남의 질문들을 읽어보세요. 여러분이 곧 만나게 될 에러들입니다. 6. 위에 적은 내용을 명심하지 않으시면 백날 강좌를 봐도(제 강좌가 아니더라도) 실력이 늘지 않고 그냥 코딩쇼 관람 및 한컴타자연습을 한 셈이 될 겁니다.

  • node.js
  • mysql
  • mongodb
  • express
  • typescript
  • socket.io
  • jwt
박예원[ 학부재학 / 컴퓨터융합 댓글 1 좋아요 0 조회수 344

그럼 그걸 다 들어야 하나요?

미해결

[웹 개발 풀스택 코스] Node.js 프로젝트 투입 일주일 전 - 기초에서 실무까지

다른 강의에 테이블이 있다고 해서 가보니..파일로 있는 게 아니고 화면에 있던데.. 그러면 저 처럼 그런 강의가 필요 없는 사람은..그걸 다 보고 만들라는 건가요? 그러기엔 시간이 아까운데요? 하루죙일..개발 하다가 왔는데..그걸 보고 일일이 쳐서 만들라는 건 좀 아니지 않나요?

  • node.js
  • mysql
  • mongodb
  • express
  • 웹-크롤링
  • socket.io
민경언 댓글 1 좋아요 0 조회수 297

작업형1 모의문제3 7번문제

해결됨

[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)

학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! 질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요 먼저 유사한 질문이 있었는지 검색해보세요 df = df.T df.head() mean_2001 = df[2001].mean() mean_2003 = df[2003].mean() a = sum(df[2001] > mean_2001) b = sum(df[2003] < mean_2003) print(a+b) 이렇게 작성하면 결과가 다르게 나오는데,, 어디서 잘못된 것일까요?

  • python
  • 머신러닝
  • 빅데이터
  • pandas
  • 빅데이터분석기사
댓글 1 좋아요 0 조회수 354

useSwr 여러컴포넌트에 사용가능한가요

미해결

Slack 클론 코딩[실시간 채팅 with React]

workSpace 에도 useSwr 로 유저데이터랑 채널데이터 요청하고 모달안에서도 유저데이터랑 채널데이터 요청하는데 이러면 불필요한 요청이 모달하나 띄운다고 실행되는거 아닌가요? workSpace에서 revalidate 함수만 넘겨서 하면 어떤가요?

  • react
  • 웹팩
  • typescript
  • socket.io
  • babel
  • 클론코딩
쵸잉 댓글 1 좋아요 0 조회수 359

코드에 대한 질문이 잇습니다.

미해결

Slack 클론 코딩[실시간 채팅 with React]

강의를 전부 진행한지 시간이 좀 된 상태에서 프로젝트 리팩토링중 이해가 안되는 부분이 있어 질문드립니다. 아래 의문점에 대해 확인과 의견을 부탁드립니다. 작성된 코드는 제로초님의 front / nest-typeorm 에서 가져온 코드입니다. 의문점 : 채팅 데이터 전송에 웹소켓이 역할을 하지 않는것 같다. 그렇게 생각한 근거 : 1-1 : useSocket을 이용해서 소켓에 연결하는데 ws-${workspace} 의 message에 onMessage 함수를 연결하고 있다 const Channel = () => { const [socket] = useSocket(workspace); useEffect(() => { socket?.on('message', onMessage); return () => { socket?.off('message', onMessage); }; }, [socket, onMessage]); } const useSocket = (workspace?: string): [Socket | undefined, () => void] => { const disconnect = useCallback(() => { if (workspace && sockets[workspace]) { console.log('소켓 연결 끊음'); sockets[workspace].disconnect(); delete sockets[workspace]; } }, [workspace]); if (!workspace) { return [undefined, disconnect]; } if (!sockets[workspace]) { sockets[workspace] = io(`${backUrl}/ws-${workspace}`, { transports: ['websocket'], }); console.info('create socket', workspace, sockets[workspace]); sockets[workspace].on('connect_error', (err) => { console.error(err); console.log(`connect_error due to ${err.message}`); }); } return [sockets[workspace], disconnect]; }; 1-2 : 백엔드에서 채팅을 수신받는 createWorkspaceChannelChats는 ws-${url}-${chatWithUser.ChannelId} 의 message에 받아온 채팅을 보내고 있다. async createWorkspaceChannelChats( url: string, name: string, content: string, myId: number, ) { const channel = await this.channelsRepository .createQueryBuilder('channel') .innerJoin('channel.Workspace', 'workspace', 'workspace.url = :url', { url, }) .where('channel.name = :name', { name }) .getOne(); const chats = new ChannelChats(); chats.content = content; chats.UserId = myId; chats.ChannelId = channel.id; const savedChat = await this.channelChatsRepository.save(chats); const chatWithUser = await this.channelChatsRepository.findOne({ where: { id: savedChat.id }, relations: ['User', 'Channel'], }); this.eventsGateway.server // .of(`/ws-${url}`) .to(`/ws-${url}-${chatWithUser.ChannelId}`) .emit('message', chatWithUser); } 2 : 네트워크 탭의 웹소켓 메시지에 채팅내역 수신내역이 남지 않는다 이미지가 보일지는 모르겟지만 빨간 박스가 새로 전송한 채팅이고 정상적으로 수신받으면 네트워크 탭에 messag에 내역이 남아야 하는걸로 알고 있는데 남지 않는걸로 확인됩니다. 3 : 웹페이지에서 포커스를 유지한 상태로 모바일에서 입력시 채팅이 전송되지 않음 왜 채팅이 정상적으로 전송된거 처럼 보일까 생각해보니 swr이 브라우저를 포커스 아웃후 재 포커스하면 채팅데이터를 다시 가져오는걸로 추측하여 웹페이지 포커스 유지중 모바일로 테스트해보니 채팅이 전송되지 않습니다.

  • react
  • 웹팩
  • typescript
  • socket.io
  • babel
  • 클론코딩
최석우 댓글 1 좋아요 1 조회수 429

웹드라이버 오류

미해결

실습으로 끝장내는 웹 크롤링과 웹 페이지 자동화 & 실전 활용

driver = webdriver.Chrome () 여기서 계속 오류가 나는데요. 혹시 최근에 바뀐게 있나요? 강의 내용 외 개인적인 실습 사이트의 질문은 답변이 제공되지 않습니다. 문제가 생긴 코드, 에러 메세지 등을 꼭 같이 올려주셔야 빠른 답변이 가능합니다. 코드를 이미지로 올려주시면 실행이 불가능하기 때문에 답변이 어렵습니다. 답변은 바로 제공되지 않을 수 있습니다. 실력 향상을 위해서는 직접 고민하고 검색해가며 해결하는 게 가장 좋습니다.

  • python
  • 웹-크롤링
  • selenium
  • beautifulsoup
니키부 댓글 3 좋아요 0 조회수 1968

윌콕슨 검정 질문입니다!

해결됨

[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)

학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! 질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요 먼저 유사한 질문이 있었는지 검색해보세요 무게에서 - 120을 뺀 이유가 무엇인가요?

  • python
  • 머신러닝
  • 빅데이터
  • pandas
  • 빅데이터분석기사
화이팅 댓글 1 좋아요 0 조회수 320

인기 태그

인프런 TOP Writers

주간 인기글