묻고 답해요
164만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결쉽게 배우는 Webpack
추가 강좌 개설해 주시면 어떨런지요? 시간이 되신다면요^^
안녕하세요 캡틴판교님 오랜만에 인사드리네요 점점더 왕성한 활동을 하셔서 너무 보기 좋습니다. 저도 덕분에 여러 프로젝트에서 Vue.js Webpack을 사용하여 효율적이고 재미있게 진행했습니다. 몇년 후에는 JS로 모바일 App을 거의 Native 수준으로 구현할 수 있으리라 생각합니다. 혹시 시간되실 때 Ionic Vue 나 PWA 에 대한 깊이 있는 실전 프로젝트를 더 다루어 주신다면 매우 유익하고 웹 프론트 개발자가 앱 영역에 도전하는데 많은 도움과 영향을 주실 수 있으리라 믿습니다. 항상 솔직 담백함과 겸허한 열정으로 지식을 공유하시는 캡틴판교님 진정한 엔지니어 이십니다. 항상 감사 드립니다. ^^
-
미해결애플 웹사이트 인터랙션 클론!
푸터 문제
7:45까지 똑같이 따라했는데 footer인 주황색 박스가 상하좌우로 공간이 생겨요. 선생님껀 푸터 양옆이 꽉차있는데 제껀 왜이러죠??
-
미해결[C#과 유니티로 만드는 MMORPG 게임 개발 시리즈] Part1: C# 기초 프로그래밍 입문
클래스의 heap 할당
스택과 달리, heap은 프로그램 실행 중간에 동적으로 할당되는 메모리 공간이라고 알고 있습니다. 질문1)그렇다면 동적 할당이란 무엇인가요?실행 도중에 동적으로 할당 받는다는게 어떤 경우이고어떤 의미인지 잘 모르겠습니다 질문2)클래스의 어떤 부분이 동적 할당이라는 건가요?구조체와 똑같이 변수 할당하고 메소드도 있고 한데, 이유가 매우 궁금합니다.
-
미해결[리뉴얼] React로 NodeBird SNS 만들기
쿠키 & 세션 질문
안녕하세요^^쿠키 와 세션에 관해서 질문이 있습니다.1. 로그인 구현할때 express-session을 통해서 연습을 하고 있는데 서버가 세션을 보내고 브라우저는 쿠키를 받는다.여기서 쿠키가 암호화가 되는이유가 express-session의옵션값으로 secret값을 가지고 해싱을 한 후 브라우저에게 주기 때문에 쿠키값이 해싱이된다. 라고 이해를 하고 있습니다.맞나연?그리고 요청이 올때는 쿠키값을 해독한 다음req.session에 들어오는 건가요??2. 그리고 로그인 요청이 올때 세션에 있는 유저 정보와 데이터베이스에 있는 유저랑 매칭 후 있으면 로그인을 시킨다.여기서도 express-session으로 구현을 해보았는데 // 요청 온 아이디와 일치하는게 데이터베이스에 있다면req.session.userId = 변수.id;이부분에서 여러사용자가 로그인 요청이 올수도 있기때문에 req.session에userId 값들을 배열로 담는것이 맞나요? ex) req.session.userId = [];req.session.userId.push(변수.id);제가 잘못생각한게 있으면 고쳐주시면 감사하겠뜹니다.
-
미해결[개정판] 파이썬 머신러닝 완벽 가이드
예제 코드와 관련해서
from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score import pandas as pd import warnings warnings.filterwarnings('ignore') # 결정 트리에서 사용한 get_human_dataset( )을 이용해 학습/테스트용 DataFrame 반환 X_train, X_test, y_train, y_test = get_human_dataset() get_human_dataset() # 랜덤 포레스트 학습 및 별도의 테스트 셋으로 예측 성능 평가 rf_clf = RandomForestClassifier(random_state=0) rf_clf.fit(X_train , y_train) pred = rf_clf.predict(X_test) accuracy = accuracy_score(y_test , pred) print('랜덤 포레스트 정확도: {0:.4f}'.format(accuracy)) 해당 코드 실행시 나오는 에러 구문입니다. 제가 타이핑 한 구문도 아니고 퍼펙트 가이드에 있는 주피터 노트북 구문 그대로 복사 붙여넣기를 했음에도 불구하고 에러가 나옵니다. 그 전에도 이런 상황과 비슷하게 퍼펙트 가이드 폴더에 있는 주피터 노트북으로 실행을 했음에도 불구하고 에러가 나오는 경우가 몇번 있었습니다.
-
미해결파이썬 알고리즘 문제풀이 입문(코딩테스트 대비)
안녕하세요. wrong answer가 뜨는경우
답이 전부 틀렸다고 나옵니다 in1~5, out1~5 까지 제가 직접 숫자를 넣어서 프로그램 돌려보면 답이 다 맞는데 채점기 돌리면wrong answer가 뜹니다 어떤게 잘못된걸까요...?
-
미해결[리뉴얼] React로 NodeBird SNS 만들기
제가 passport_Google_OAuth_2.0 을 따라서 작성을 한 후 saga에서 서버로 /google/ 쿼리를 넣었더니 cors 에러가 뜹니다
제가 직접 주소창에 (서버포트:3090) localhost:3090/google을 치면 제대로 제 google-email을 가져오지만 saga를 통해서 (client포트: 9229) localhost:3090/google을 넣으면 cors policy가 뜹니다 saga에서 서버로 가는 요청은 제대로 가는데 resource 서버로 가는 요청이 cors에 막히는 것 같습니다. 제 생각에는 front server에서 직접 google server에 인증을 요청하는 게 방법일 수 있을거 같은데 맞나요? 지금 제 코드는 saga에서 요청을 보내면 backend에서 authenticate를 하고 있습니다. 그래서 redirect를 하면서 cors 에러가 생기는게 아닐까? 해서 그랬습니다. 소스코드는 githhub에 있습니다. https://github.com/JeongJin984/Kit-Books 밑은 에러 입니다.
-
해결됨실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발
디비에 값이 입력이 안됩니다
안녕하세요 ~ 계속 디비에 값이 입력이 안됩니다.. 테이블 생성까지는 잘되는데 오류도안나오구 뭐가 문제인지 감이 안잡힙니다 그리고 확인해보니깐 저는 transactional rollback 로그가 계속 안찍힙니다.. gradle 빌드가 너무 오래걸려서 인텔리j로 빌드로 되게 옵션을 설정을 한 상태입니다 The Class-Path manifest attribute in C:\Users\User\.gradle\caches\modules-2\files-2.1\org.glassfish.jaxb\jaxb-runtime\2.3.1\dd6dda9da676a54c5b36ca2806ff95ee017d8738\jaxb-runtime-2.3.1.jar referenced one or more files that do not exist: file:/C:/Users/User/.gradle/caches/modules-2/files-2.1/org.glassfish.jaxb/jaxb-runtime/2.3.1/dd6dda9da676a54c5b36ca2806ff95ee017d8738/jaxb-api-2.3.1.jar,file:/C:/Users/User/.gradle/caches/modules-2/files-2.1/org.glassfish.jaxb/jaxb-runtime/2.3.1/dd6dda9da676a54c5b36ca2806ff95ee017d8738/txw2-2.3.1.jar,file:/C:/Users/User/.gradle/caches/modules-2/files-2.1/org.glassfish.jaxb/jaxb-runtime/2.3.1/dd6dda9da676a54c5b36ca2806ff95ee017d8738/istack-commons-runtime-3.0.7.jar,file:/C:/Users/User/.gradle/caches/modules-2/files-2.1/org.glassfish.jaxb/jaxb-runtime/2.3.1/dd6dda9da676a54c5b36ca2806ff95ee017d8738/stax-ex-1.8.jar,file:/C:/Users/User/.gradle/caches/modules-2/files-2.1/org.glassfish.jaxb/jaxb-runtime/2.3.1/dd6dda9da676a54c5b36ca2806ff95ee017d8738/FastInfoset-1.2.15.jar,file:/C:/Users/User/.gradle/caches/modules-2/files-2.1/org.glassfish.jaxb/jaxb-runtime/2.3.1/dd6dda9da676a54c5b36ca2806ff95ee017d8738/javax.activation-api-1.2.0.jar . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.1.17.BUILD-SNAPSHOT) 2020-07-31 20:13:32.572 INFO 1008 --- [ restartedMain] jpashop.jpabook.JpabookApplication : Starting JpabookApplication on DESKTOP-H66EP9G with PID 1008 (C:\Users\User\Spring\jpabook\out\production\classes started by User in C:\Users\User\Spring\jpabook) 2020-07-31 20:13:32.576 INFO 1008 --- [ restartedMain] jpashop.jpabook.JpabookApplication : No active profile set, falling back to default profiles: default 2020-07-31 20:13:32.679 INFO 1008 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable 2020-07-31 20:13:32.680 INFO 1008 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG' 2020-07-31 20:13:34.406 INFO 1008 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode. 2020-07-31 20:13:34.456 INFO 1008 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 35ms. Found 0 JPA repository interfaces. 2020-07-31 20:13:35.837 INFO 1008 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2020-07-31 20:13:36.026 INFO 1008 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2020-07-31 20:13:36.027 INFO 1008 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37] 2020-07-31 20:13:36.289 INFO 1008 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2020-07-31 20:13:36.290 INFO 1008 --- [ restartedMain] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3610 ms 2020-07-31 20:13:36.563 INFO 1008 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... 2020-07-31 20:13:36.674 INFO 1008 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. 2020-07-31 20:13:36.774 INFO 1008 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [ name: default ...] 2020-07-31 20:13:36.877 INFO 1008 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate Core {5.3.17.Final} 2020-07-31 20:13:36.879 INFO 1008 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found 2020-07-31 20:13:37.087 INFO 1008 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final} 2020-07-31 20:13:37.291 INFO 1008 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect 2020-07-31 20:13:38.041 DEBUG 1008 --- [ restartedMain] org.hibernate.SQL : drop table member if exists 2020-07-31 20:13:38.045 DEBUG 1008 --- [ restartedMain] org.hibernate.SQL : drop sequence if exists hibernate_sequence 2020-07-31 20:13:38.048 DEBUG 1008 --- [ restartedMain] org.hibernate.SQL : create sequence hibernate_sequence start with 1 increment by 1 2020-07-31 20:13:38.048 DEBUG 1008 --- [ restartedMain] org.hibernate.SQL : create table member ( id bigint not null, username varchar(255), primary key (id) ) 2020-07-31 20:13:38.050 INFO 1008 --- [ restartedMain] o.h.t.schema.internal.SchemaCreatorImpl : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@70dc37ec' 2020-07-31 20:13:38.053 INFO 1008 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 2020-07-31 20:13:38.075 INFO 1008 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729 2020-07-31 20:13:38.544 INFO 1008 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 2020-07-31 20:13:38.624 WARN 1008 --- [ restartedMain] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning 2020-07-31 20:13:38.683 INFO 1008 --- [ restartedMain] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: class path resource [static/index.html] 2020-07-31 20:13:39.089 INFO 1008 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2020-07-31 20:13:39.095 INFO 1008 --- [ restartedMain] jpashop.jpabook.JpabookApplication : Started JpabookApplication in 7.38 seconds (JVM running for 8.413)
-
미해결프로그래밍, 데이터 과학을 위한 파이썬 입문
다른 방식으로 코드를 작성해보았습니다.
수업 열심히 듣고 있습니다. 좋은 수업 감사합니다. 저는 연속적인 구구단 입력에 대한 코드를 다음과 같이 작성해보았습니다. ============================================= user_input = int(input("구구단 몇단을 작성할까요(1~9)? 종료하시려면 0을 입력해주세요. ")) while (user_input < 0 and user_input > 9): print("숫자를 잘못 입력하셨습니다. 다시 입력해주세요") user_input = int(input()) while(user_input != 0): print("구구단", user_input,"단을 작성합니다.") for i in range(1,10): result = user_input * i print(user_input, "X", i, "=", result) user_input = int(input("구구단 몇단을 작성할까요? ")) if(user_input == 0): break print("구구단 작성을 종료합니다.") ============================================= 개선점이나 잘못된 점을 알려주시면 감사하겠습니다.
-
미해결인터랙티브 웹 개발 제대로 시작하기
여기서 변수설정해줄때 질문있습니다.
this.lastScrollTop을 선언해줄때 계속 코드를 작성하던 이벤트 함수 안이나 init함수 안에서 선언해주는것이 아닌 생성자 함수를 만들때 넣어주시는데 꼭 그렇게 하는 이유가 있나요? 혹시 나중에 다른 추가적인 함수들에서 그 변수를 쓸 경우를 고려하셔서 그렇게 하시는 건가요?
-
미해결실전! 스프링 부트와 JPA 활용2 - API 개발과 성능 최적화
JPA Delete 동작이 궁금합니다.
안녕하세요. 좋은 강의를 제공해주신 덕분에 JPA를 열심히 공부하고 있습니다. JPA 사용 중에 궁금한 점이 있는데요 delete동작 방식을 보니, em.find로 entity를 조회 후에 em.remove순으로 query가 동작하고 있습니다. Mysql에서 null인 값을 조건절로 삭제해봐도 에러는 발생하지 않는데, JPA만의 특별한 이유가 있을까요? 두 번째로 궁금한 점도 있습니다ㅎㅎ JPA에서는 foreign key 제약조건을 위반하지 않기 위해서 모든 sql이 아래의 순서로 동작한다고 합니다. 1. Insert, in the order they were performed 2. Updates 3. Deletion of collection elements 4. Insertion of collection elements 5. Deletes, in the order they were performed 위의 조건으로 인해 하나의 transaction안에서 unique key걸린 값을 remove후 save하면 duplicate error가 발생하는데요. 혹시 이것도 JPA만의 특별한 이유가 있는지 너무너무 궁금합니다!
-
미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
회원 가입 할때 에러나는 부분들이 있어서여
안녕하세여 john ahn 님 저 ㅈㅅ한데 처음부터 강의를 다시 듣는중인데 이부분에서 다시 에러가 나서여 저번에 알려주셨던것도 같은데 좀 되서 잊어버렸어요 ㅈㅅ 회원 가입한뒤에 몽고 디비에서 다음과 같이 확인이 되고 회원가입 두번째 시도에 에러가 발생해서여 왜 그런지 알려주시면 대단히 감사여postman의 메세지는 result: { "success": false, "err": { "driver": true, "name": "MongoError", "index": 0, "code": 11000, "keyPattern": { "email": 1 }, "keyValue": { "email": null } } } 몽고 디비의 저장 형식도 좀 이상하고 두번째 회원 가입이 실패하는것도 이해가 안가여 아이디를 바꿔서 회원 가입 해도 두번째부터 에러가 발생해여
-
미해결프로그래밍 시작하기 : 파이썬 입문 (Inflearn Original)
설치오류
파이썬이랑 아톰 설치는 되는데 아톰에서 autocomplete-python, script가 다운이 안되고 deprecated라고 뜨네요..
-
미해결웹 게임을 만들며 배우는 자바스크립트
children이 호출이 안되요ㅠㅠ
안녕하세요 선생님 강의랑 조금 다른 방식으로 btn.addEventListener("click", makeArray); 에서 table안에 tr, td 만드는 makeArray함수호출하고 (참고로 tbody같은 html요소들은 makeArray밖의 맨위에 이미 특정해놨어요) 이 함수안에서 randomNumberForDigging(horiz, verti, numMine);로 폭탄위치정할 랜덤 Array 만드는 함수 호출을 하는데 이상한것이 makeArray함수에서는 tbody.children[특정n]하면 호출되는데 randomNumberForDigging이 함수에서는 호출이 안되요. 근데 randomNumberForDigging여기서 console.log(tbody.children[특정n])은 undefined인데 console.log(tbody.children) 은 htmlcollection이라며 호출이 되요..이틀동안 원인을 찾고있는데 모르겠어요ㅠㅠ
-
데브옵스(DevOps)를 위한 쿠버네티스 마스터
GCP, 쿠버네티스 질문입니다!!
삭제된 글입니다
-
해결됨[리뉴얼] React로 NodeBird SNS 만들기
로그인 시도중 backend 에서 에러가 발생하면서 로그인이 되지 않습니다. 작성한 코드는 강사님이 작성하신 코드와 차이가 없는것 같습니다.
login(option) login(Post) 아래는 backend - log 입니다. Executing (default): SELECT `id`, `email`, `nickname`, `password`, `createdAt`, `updatedAt` FROM `Users` AS `User` WHERE `User`.`email` = 'test@test.com'; Executing (default): INSERT INTO `Users` (`id`,`email`,`nickname`,`password`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?); Executing (default): SELECT `id`, `email`, `nickname`, `password`, `createdAt`, `updatedAt` FROM `Users` AS `User` WHERE `User`.`email` = 'test@test.com'; (node:11018) UnhandledPromiseRejectionWarning: Error: Include unexpected. Element has to be either a Model, an Association or an object. at Function._conformInclude (/Users/imac/Desktop/nodebird study/back/node_modules/sequelize/lib/model.js:383:11) at /Users/imac/Desktop/nodebird study/back/node_modules/sequelize/lib/model.js:319:59 at Array.map (<anonymous>) at Function._conformIncludes (/Users/imac/Desktop/nodebird study/back/node_modules/sequelize/lib/model.js:319:39) at Function._baseMerge (/Users/imac/Desktop/nodebird study/back/node_modules/sequelize/lib/model.js:786:10) at Function._defaultsOptions (/Users/imac/Desktop/nodebird study/back/node_modules/sequelize/lib/model.js:823:17) at Function._injectScope (/Users/imac/Desktop/nodebird study/back/node_modules/sequelize/lib/model.js:3224:10) at Function.findAll (/Users/imac/Desktop/nodebird study/back/node_modules/sequelize/lib/model.js:1694:10) at Function.findOne (/Users/imac/Desktop/nodebird study/back/node_modules/sequelize/lib/model.js:1905:23) at /Users/imac/Desktop/nodebird study/back/routes/user.js:25:56 (node:11018) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2) (node:11018) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. 에러 메세지를 읽은 결과... 원인이 두가지로 생각되는데요 1. routes/user.js 에 route /login 부분의 요소가 연관 모델이 아니다. 2. routes/user.js 에 route /login 함수를 try catch 로 묶어 줘라. 제가 이해한것이 맞는지 모르겠네요.. routes/user.js const express = require('express'); const bcrypt = require('bcrypt'); const passport = require('passport'); const { User, Post } = require('../models'); const router = express.Router(); // 로그인 login // 미들웨어 확장 router.post('/login', (req, res, next) => { passport.authenticate('local', (err, user, info) => { // 서버 에러, 성공, 클라이언트 에러 if (err) { console.error(err); return next(err); } if (info) { return res.status(401).send(info.reasone); // 401: 허가되지 않음 , 403: 금지 } return req.login(user, async (loginErr) => { // passport login error 시 if (loginErr) { console.error(loginErr); return next(loginErr); } const fullUserWithoutPassword = await User.findOne({ where: { id: user.id }, // attributes: ['id', 'nickname','email'], attributes: { exclude: ['password'] }, include: [{ model: Post, attributes: ['id'], }, { medel: User, as: 'Followings', attributes: ['id'], }, { model: User, as: 'Followers', attributes: ['id'], }] }) // res.setHeader('Cookie', 'cxlhy') return res.status(200).json(fullUserWithoutPassword); }); })(req, res, next); }); // 로그아웃 logout router.post('/logout', (req, res) => { req.logout(); req.session.destroy(); // session 에 저장된 쿠키와 id 를 지운다. res.send('ok'); // 로그아웃 성공 }); // 회원가입 signup router.post('/', async (req,res, next) => { // POST /user try { const exUser = await User.findOne({ where: { email: req.body.email, } }); if (exUser) { return res.status(403).send('이미 사용 중인 아이디입니다.'); // 응답 } const hashedPassword = await bcrypt.hash(req.body.password, 12); // 10 ~ 13 - 해쉬화 한다. await User.create({ email: req.body.email, nickname: req.body.nickname, password: hashedPassword, }); // res.json(); // res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000'); // res.setHeader('Access-Control-Allow-Origin', '*'); res.status(200).send('ok'); // res.status(200).send('ok'); 응답 } catch(error) { console.error(error); next(error); // status 500 } }); // router.delete('/', (req,res) => { // DELETE /user // res.json({id: 1 }); // }); module.exports = router; app.js const express = require('express'); const cors = require('cors'); const session = require('express-session'); const cookieParser = require('cookie-parser'); const passport = require('passport'); const dotenv = require('dotenv'); const postAPIRouter = require('./routes/post'); const userAPIRouter = require('./routes/user'); const db = require('./models'); const passportConfig = require('./passport'); dotenv.config(); const app = express(); db.sequelize.sync() .then(() => { console.log('db 연결 성공'); }) .catch(console.error); passportConfig(); app.use(cors({ // origin: 'https://nodebird.com', // https://nodebird.com 에서 온 요청만 허용하겠다. origin: '*', // 모든 요청 허용 // credentials: false, // })); app.use(express.json()); // front server 에서 json 형식으로 데이터를 보냈을때 req.body 안에 data를 넣어준다. app.use(express.urlencoded({ extended: true})); // from submit 했을때 urlencoded 방식으로 변환해준다. app.use(cookieParser(process.env.COOKIE_SECRET)); app.use(session({ saveUninitialized: false, resave: false, secret: process.env.COOKIE_SECRET, })); app.use(passport.initialize()); app.use(passport.session()); app.use('/post', postAPIRouter); app.use('/user', userAPIRouter); app.listen(3065, () => { console.log('서버 실행 중') }); models/user.js module.exports = (sequelize, DataTypes) => { const User = sequelize.define('User', { // Mysql에는 users 테이블 생성 // id가 기본적으로 들어있다. email: { type: DataTypes.STRING(30), // INTEGER: 정수, FLOAT: 소수(실수) BOOLEAN, FLOAT allowNull: false, // 필수 unique: true, // 고유한 값 }, nickname: { type: DataTypes.STRING(30), allowNull: false, // 필수 }, password: { type: DataTypes.STRING(100), allowNull: false, // 필수 }, }, { charset: 'utf8', collate: 'utf8_general_ci' // 한글 저장 }); User.associate = (db) => { db.User.hasMany(db.Post); db.User.hasMany(db.Comment); // Liked user 가 좋아요를 누른 post 를 가져온다.. db.User.belongsToMany(db.Post, { through: 'Like', as: 'Liked' }); db.User.belongsToMany(db.User, { through: 'Follow', as: 'Followers', foreignKey: 'FollowingId'}); db.User.belongsToMany(db.User, { through: 'Follow', as: 'Followings', foreignKey: 'FollowerId'}); }; return User; models/post.js module.exports = (sequelize, DataTypes) => { const Post = sequelize.define('Post', { // Mysql에는 posts 테이블 생성 // id가 기본적으로 들어있다. content: { type: DataTypes.TEXT, allowNull: false, }, // RetweetId }, { charset: 'utf8mb4', collate: 'utf8mb4_general_ci' // 이모티콘 저장 }); Post.associate = (db) => { db.Post.belongsTo(db.User); db.Post.belongsToMany(db.Hashtag, { through: 'PostHashtag'} ); db.Post.hasMany(db.Comment); db.Post.hasMany(db.Image); // user post 테이블간에 like 테이블이 생기고.. as 에 따라서 post.getLikers 처럼 게시글 좋아요.. 누른 user 를 가져온다. // Likers 좋아요를 누른 user 를 가져온다. db.Post.belongsToMany(db.User, { through: 'Like', as: 'Likers' }); db.Post.belongsTo(db.Post, { as: 'Retweet' }) }; return Post; } models/comment.js module.exports = (sequelize, DataTypes) => { const Comment = sequelize.define('Comment', { // Mysql에는 comments 테이블 생성 // id가 기본적으로 들어있다. content: { type: DataTypes.TEXT, allowNull: false, }, // UserId: 1 // PostId: 1 }, { charset: 'utf8mb4', collate: 'utf8mb4_general_ci' // 한글 저장 }); Comment.associate = (db) => { db.Comment.belongsTo(db.User); db.Comment.belongsTo(db.Post); }; return Comment; } sagas/user.js import { all, put, fork, takeLatest, delay, call } from 'redux-saga/effects'; import axios from 'axios'; import { LOG_IN_REQUEST, LOG_IN_SUCCESS, LOG_IN_FAILURE, LOG_OUT_REQUEST, LOG_OUT_SUCCESS, LOG_OUT_FAILURE, SIGN_UP_REQUEST, SIGN_UP_SUCCESS, SIGN_UP_FAILURE, FOLLOW_REQUEST, FOLLOW_SUCCESS, FOLLOW_FAILURE, UNFOLLOW_REQUEST, UNFOLLOW_SUCCESS, UNFOLLOW_FAILURE, } from '../reducers/user'; function followAPI(data) { return axios.post('/api/follow', data); } function* follow(action) { try { // yield put({ // type: 'FOLLOW_REQUEST', // }); // const result = yield call(followAPI, action.data); // ex> const result = yield call(logInAPI, action.data, a, b, c); a, b, c 인자를 추가시 yield delay(1000); // throw new Error('') // 아래 catch 로 넘어간다. yield put({ type: FOLLOW_SUCCESS, data: action.data, }); } catch (err) { yield put({ // put => dispatch 다. type: FOLLOW_FAILURE, data: err.response.data, }); } } function unfollowAPI(data) { return axios.post('/api/unfollow', data); } function* unfollow(action) { try { // yield put({ // type: 'UNFOLLOW_REQUEST', // }); // const result = yield call(unfollowAPI, action.data); // ex> const result = yield call(logInAPI, action.data, a, b, c); a, b, c 인자를 추가시 yield delay(1000); // throw new Error('') // 아래 catch 로 넘어간다. yield put({ type: UNFOLLOW_SUCCESS, data: action.data, }); } catch (err) { yield put({ // put => dispatch 다. type: UNFOLLOW_FAILURE, data: err.response.data, }); } } function signUpAPI(data) { return axios.post( '/user', data); // localhostUrl ( http://localhost:3065 ) + /user } function* signUp(action) { try { // yield put({ // type: 'LOG_IN_REQUEST', // }); const result = yield call(signUpAPI, action.data); // ex> const result = yield call(logInAPI, action.data, a, b, c); a, b, c 인자를 추가시 // yield delay(1000); // throw new Error('') // 아래 catch 로 넘어간다. console.log(result); yield put({ type: SIGN_UP_SUCCESS, // data: result.data, }); } catch (err) { console.error(err); yield put({ // put => dispatch 다. type: SIGN_UP_FAILURE, data: err.response.data, }); } } function logOutAPI() { return axios.post('/api/logout'); } function* logOut() { try { // yield put({ // type: 'LOG_OUT_REQUEST', // }); // const result = yield call(logOutAPI); yield delay(1000); yield put({ type: LOG_OUT_SUCCESS, }); } catch (err) { yield put({ // put => dispatch 다. type: LOG_OUT_FAILURE, error: err.response.data, }); } } function logInAPI(data) { return axios.post('/user/login', data); } function* logIn(action) { try { console.log('saga logIn'); // yield put({ // type: 'LOG_IN_REQUEST', // }); const result = yield call(logInAPI, action.data); console.log(result); // ex> const result = yield call(logInAPI, action.data, a, b, c); a, b, c 인자를 추가시 // yield delay(1000); yield put({ type: LOG_IN_SUCCESS, data: result.data, }); } catch (err) { console.error(err); yield put({ // put => dispatch 다. type: LOG_IN_FAILURE, error: err.response.data, }); } } function* watchFollow() { yield takeLatest(FOLLOW_REQUEST, follow); // take =>logIn 액션이 실행될때까지 기다리겠다. } function* watchUnFollow() { yield takeLatest(UNFOLLOW_REQUEST, unfollow); // take =>logIn 액션이 실행될때까지 기다리겠다. } function* watchLogIn() { yield takeLatest(LOG_IN_REQUEST, logIn); // take =>logIn 액션이 실행될때까지 기다리겠다. } function* watchLogOut() { yield takeLatest(LOG_OUT_REQUEST, logOut); } function* watchSignUp() { yield takeLatest(SIGN_UP_REQUEST, signUp); // take =>logIn 액션이 실행될때까지 기다리겠다. } export default function* userSaga() { yield all([ fork(watchFollow), fork(watchUnFollow), fork(watchLogIn), fork(watchLogOut), fork(watchSignUp), ]); } sagas/index.js // all fork call put delay debounce throttle takeLatest tabkeEvery takeLeding taekMaybe import { all, fork } from 'redux-saga/effects'; import axios from 'axios'; import postSaga from './post'; import userSaga from './user'; import { localhostUrl } from '../config/config'; axios.defaults.baseURL = localhostUrl; export default function* rootSaga() { yield all([ // all 은 배열을 받아서 배열안에 있는 명령들을 한번에 실행 시켜준다. fork(postSaga), fork(userSaga), ]); }; front/config/config.js export const domainUrl = 'http://api.nodebird.com'; export const localhostUrl = 'http://localhost:3065';
-
미해결Vue.js 끝장내기 - 실무에 필요한 모든 것
안녕하세요. 질문이 있습니다.
태그 작성하고 저장하면 자동적으로 포멧팅 하는데 br, img, input 들이 뒤에 /가 붙어서 나오더라구요.. <br/> <img/> <input/> 이렇게요~ 해당 기능을 끌 수 있을까요?? 확인 부탁 드립니다. 감사합니다.
-
미해결홍정모의 따라하며 배우는 C++
random shuffle이 안되는데 이유를 모르겠습니다.
#include <iostream> #include <vector> #include <algorithm> using namespace std; class Cents { private: int m_cents; public: Cents(int cents = 0) { m_cents = cents; } int getCents() const { return m_cents; } int& getCents() { return m_cents; } friend std::ostream& operator << (std::ostream& out, const Cents& cents) { out << cents.m_cents; return out; } }; int main() { vector<Cents> arr(20); for (unsigned i = 0; i < 20; ++i) { arr[i].getCents() = i; } std::random_shuffle(begin(arr), end(arr)); for (auto& e : arr) { cout << e << " "; } cout << endl; return 0; } 강의 내용 그대로 친 것 같은데 random 셔플부분만 std에 존재하지 않는다고 계속 에러나네요.
-
해결됨스프링과 JPA 기반 웹 애플리케이션 개발
엔티티에 저장이 안되는 문제에 대한 문의
안녕하세요. 강의 잘 보았습니다. 강의 도움 받아서 테스트 진행해보고 있는데요. 저장이 안되는 부분에 대해 문의 드려봅니다. Car, Camp 엔티티가 있고 Car 전체 데이터 읽어서 특정 필드의 값을 Camp 에서 찾아서 업데이트하는 로직입니다. if (carRepository.count() > 0) { carRepository.findAll().stream().forEach(s -> { String campName = s.getCampEngName(); Optional<Car> car = carRepository.findById(s.getId()); Camp camp = campRepository.findByEngName(campName); if (camp != null) { car.ifPresent(m -> m.setNote(camp.getKorName())); } });} 해당 부분 코드는 이렇게 했는데, 수행 후에 실제 Car 엔티티의 note 값이 변경이 안되어있습니다. 로그 찍어보면 campName 값은 일일이 잘 가져오고 있는데 setNote로 저장이 안됩니다. 트랜젝션 문제일까요? 강의를 제대로 소화를 못했는지 원인을 못찾겠네요. ㅠㅠ 도움 부탁드립니다. 아.. 저게 수행되는 곳이, 일반 컨트롤러 통해서 들어오는게 아니라 최초 실행시점입니다.(혹시 이게 문제일까요?) @PostConstruct public void initCarData() throws IOException { ... if (carRepository.count() > 0) { } ... } 이 부분입니다.
-
미해결홍정모의 따라하며 배우는 C언어
디버깅에 대하여
강의를 따라 해보는데 강의처럼 구현이 되지 않습니다. 어떻게 해야 될까요.