수강이 제한됩니다.
다른 수강생들이 자주 물어보는 질문이 궁금하신가요?
- 미해결Node.js 교과서 - 기본부터 프로젝트 실습까지
4장에 뒷부분이 이해가 잘안됩니다.
아예 이해가 안된다기보단 어떤일을 하는진 알겠는데 코드하나하나씩 따라가기엔 모르는개념이 있습니다. 뒷부분부터 모듈 가져다 쓰던데, 일단 그냥 이대로 다음장으로 넘어가는게 좋을까요?
- 미해결Node.js 교과서 - 기본부터 프로젝트 실습까지
질문이요
제가 JWT를 통해서, 비밀번호 찾기 기능을 만들고 있습니다. 1. 유저가 아이디 이메일 입력 하고 전송버튼을 누릅니다.. 2. 서버에서, DB에있는 받은 아이디값을 조회후, DB에 유저정보가 있으면 JWT 토큰에 아이디를 넣어서 유저 이메일로 보내줍니다. 3. 유저는 이메일 안에, JWT가 쿼리로 되어있는 링크가 있고 그걸 클릭시, JWT가 verify 되면서, 비밀먼호를 바꿀수 있는 페이지로 이동시키려고 생각중입니다. 여기에서 궁금한점이, 1. JWT를 쿼리로 보내도 되는 건가요??, 그냥 완전히 노출하듯이 쿼리로 보냈는데, 보안상으로 문제가 있는건가요..? JWT 안에는 딱히 있는 값이라고는 [Id : 2 ] 이거 뿐이긴 해요... 강의에서는 헤더로 보내주셨는데, <a href= ___> </a> 이 상태로 링크+JWT를 보내는데, 헤더로 보낼 방법이 없는거 같더라구요...
- 미해결Node.js 교과서 - 기본부터 프로젝트 실습까지
add,set,remove 함수 명명규칙이 궁금합니다.
[add,set,remove] + 대문자명으로 시작한다고 하셨는데 그럼 User : User, N:M 관계에서 테이블명이 Follow인데 왜 여기서는 Following이 되는지 궁금합니다.
- 미해결Node.js 교과서 - 기본부터 프로젝트 실습까지
장소검색 서비스구현. 구글 API 키 사용 부분
안녕하세요 책&동영상 강의 보면서 스터디 중인데 책기준..13장 장소검색 서비스 질문드립니다. 구글 API 키를 발급받아서 .env 파일에 PLACES_API_KEY 값에 제가 발급받은 API키 값을 넣었는데요 서버 시작해서 웹화면에서 테스트를 하면 검색결과가 지도에 순간 표시 되다가 에러 화면으로 넘어가서요.. 개발자도구에서 에러난 부분을 마우스오버해서 보면 API키로 넘어가는 값이...제가 .env파일에 업데이트한 값이 아니라 제로님 책에 기재되어 있는 그 키값으로 넘어가더라구요 이유를 모르겠어서 질문 남깁니다^^
- 미해결Node.js 교과서 - 기본부터 프로젝트 실습까지
워크벤치 활성화 부분.
1. workbench에서 + 를 눌러서 새로만들기를 하고 root 등 입력하고 ok 를 해서 새로운 창에 들어갔습니다. 그런데 강좌와 같이 schema 버튼이 활성화가 안되어있고 connection도 STOP으로 되어있습니다. 어떻게 해결가능한가요 ? 2.이상태에서 터미널에서 sequelize db:create 을 하면 connect ECONNREFUSED 127.0.0.1:3306 에러가 뜹니다. 답변 부탁드려요 ㅠㅠ
- 미해결Node.js 교과서 - 기본부터 프로젝트 실습까지
[Error] 여러 개의 태그를 검색하고 싶으면 어떻게 해야 하나요?
const arr = ['테스트', 'test']; try{ const hash = await Hashtag.findAll({ where : { title : arr }}); console.log(hash); let post = []; post = await hash.getItems(); res.render('main', { title: 'WeAreHere 중고 & 플리마켓 SNS', posts: posts, user: req.user, }); } catch (error) { console.error(error); next(error); } 여러 개의 태그를 검색해보고 싶어서 검색하고 싶은 태그를 arr에 넣고 테스트 해봤습니다. 그러나 아래와 같은 에러만 발생하네요 ㅠㅜ hash.getItems is not a function TypeError: hash.getItems is not a function at D:\Study\Server\nodejs\nodejsLib\URI\routes\search.js:16:27 findAll을 했을 경우에는 어떻게 관계있는 로우를 조회할 수 있을까요?
- 미해결Node.js 교과서 - 기본부터 프로젝트 실습까지
전체 클라이언트 서버 관계도가 이해가지 않습니다
안녕하세요 전체 클라이언트 서버 관계도가 명확하게 이해가지 않아 질문드립니다. 아래는 제가 이해한 내용인데요 맞는지 궁금합니다. NodeBird-call - api 서버를 통해 받아온 데이터로 템플릿만 생성해준다 NodeBird-app - api 서버, 권한이 필요없다 NodeBird-api - api 서버, 권한이 필요하다 추가질문 1. NodeBird-app과 NodeBird-api를 나눈 이유는 권한이 필요한것과 불필요한 것을 나누기 위함인가요? 아니면 공개, 비공개 하기 위함인가요? 2. 만약 single page application을 사용한다면 NodeBird-call같은 서버의 역할은 무엇인가요? 번들된 스크립트를 불러오는 index.html를 만들어주거나 회원가입이나 로그인 페이지같은 템플릿 페이지를 생성해주는 역할을 하는건가요?
- 미해결Node.js 교과서 - 기본부터 프로젝트 실습까지
11.4 깃허브파일부터 몽고디비 연결이 안됩니다.
11.3까진 잘돌리면서 따라왔는데 11.4파일부터 몽고디비 세팅부터 열심히 따라 했는데 연결에러가 계속 뜹니다. 몽고디비 연결이 끊겼습니다. 연결을 재시도합니다. 몽고디비 연결 에러 MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoError: Authentication failed. at Function._getError (/Users/parks/Desktop/nodejs-book-master/ch11/11.6/gif-chat/node_modules/mongodb/lib/core/auth/scram.js:125:14) at /Users/parks/Desktop/nodejs-book-master/ch11/11.6/gif-chat/node_modules/mongodb/lib/core/auth/scram.js:175:31 at _callback (/Users/parks/Desktop/nodejs-book-master/ch11/11.6/gif-chat/node_modules/mongodb/lib/core/connection/connect.js:320:5) at Connection.messageHandler (/Users/parks/Desktop/nodejs-book-master/ch11/11.6/gif-chat/node_modules/mongodb/lib/core/connection/connect.js:349:5) at Connection.emit (events.js:210:5) at processMessage (/Users/parks/Desktop/nodejs-book-master/ch11/11.6/gif-chat/node_modules/mongodb/lib/core/connection/connection.js:368:10) at Socket.<anonymous> (/Users/parks/Desktop/nodejs-book-master/ch11/11.6/gif-chat/node_modules/mongodb/lib/core/connection/connection.js:537:15) at Socket.emit (events.js:210:5) at addChunk (_stream_readable.js:326:12) at readableAddChunk (_stream_readable.js:301:11) at Socket.Readable.push (_stream_readable.js:235:10) at TCP.onStreamRead (internal/stream_base_commons.js:182:23) { name: 'MongoError', [Symbol(mongoErrorContextSymbol)]: {} }] at Pool.<anonymous> (/Users/parks/Desktop/nodejs-book-master/ch11/11.6/gif-chat/node_modules/mongodb/lib/core/topologies/server.js:433:11) at Pool.emit (events.js:210:5) at /Users/parks/Desktop/nodejs-book-master/ch11/11.6/gif-chat/node_modules/mongodb/lib/core/connection/pool.js:562:14 at /Users/parks/Desktop/nodejs-book-master/ch11/11.6/gif-chat/node_modules/mongodb/lib/core/connection/pool.js:985:11 at callback (/Users/parks/Desktop/nodejs-book-master/ch11/11.6/gif-chat/node_modules/mongodb/lib/core/connection/connect.js:110:5) at /Users/parks/Desktop/nodejs-book-master/ch11/11.6/gif-chat/node_modules/mongodb/lib/core/connection/connect.js:367:21 at /Users/parks/Desktop/nodejs-book-master/ch11/11.6/gif-chat/node_modules/mongodb/lib/core/auth/auth_provider.js:66:11 at /Users/parks/Desktop/nodejs-book-master/ch11/11.6/gif-chat/node_modules/mongodb/lib/core/auth/scram.js:177:16 at _callback (/Users/parks/Desktop/nodejs-book-master/ch11/11.6/gif-chat/node_modules/mongodb/lib/core/connection/connect.js:320:5) at Connection.messageHandler (/Users/parks/Desktop/nodejs-book-master/ch11/11.6/gif-chat/node_modules/mongodb/lib/core/connection/connect.js:349:5) at Connection.emit (events.js:210:5) at processMessage (/Users/parks/Desktop/nodejs-book-master/ch11/11.6/gif-chat/node_modules/mongodb/lib/core/connection/connection.js:368:10) at Socket.<anonymous> (/Users/parks/Desktop/nodejs-book-master/ch11/11.6/gif-chat/node_modules/mongodb/lib/core/connection/connection.js:537:15) at Socket.emit (events.js:210:5) at addChunk (_stream_readable.js:326:12) at readableAddChunk (_stream_readable.js:301:11) { name: 'MongoNetworkError', errorLabels: [ 'TransientTransactionError' ], [Symbol(mongoErrorContextSymbol)]: {} 세팅은 그대로 따라갔는데 무슨문제인지 모르겠네요
- 미해결Node.js 교과서 - 기본부터 프로젝트 실습까지
에러에 대한 질문입니다.
User.find is not a function TypeError: User.find is not a function at D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\routes\auth.js:13:35 at Layer.handle [as handle_request] (D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\layer.js:95:5) at next (D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\route.js:137:13) at exports.isNotLoggedIn (D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\routes\middlewares.js:14:9) at Layer.handle [as handle_request] (D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\layer.js:95:5) at next (D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\layer.js:95:5) at D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\index.js:281:22 at Function.process_params (D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\index.js:335:12) at next (D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\index.js:275:10) at Function.handle (D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\index.js:174:3) at router (D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\index.js:47:12) at Layer.handle [as handle_request] (D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\layer.js:95:5) at trim_prefix (D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\index.js:317:13) at D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\index.js:284:7 at Function.process_params (D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\index.js:335:12) at next (D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\index.js:275:10) at D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\index.js:635:15 at next (D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\index.js:260:14) at Function.handle (D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\index.js:174:3) at router (D:\_Node.js\_NodeStudy_inflearn\Node-Study\NodeSNS\nodebird\node_modules\express\lib\router\index.js:47:12)오류가 이렇게 나옵니다...하지만 저는 auth.js 설정이 되어있습니다. const express = require('express'); const passport = require('passport'); const bcrypt = require('bcrypt'); const { isLoggedIn, isNotLoggedIn } = require('./middlewares'); const { User } = require('../models'); const router = express.Router(); // POST /auth/join (회원가입) router.post('/join', isNotLoggedIn, async (req, res, next) => { const { email, nick, password} = req.body; try { const exUser = await User.find({ where: { email } }); if (exUser) { req.flash('joinError', '이미 가입된 이메일입니다.'); return res.redirect('/join'); } // console.time('암호화 시간'); const hash = await bcrypt.hash(password, 17); // console.timeEnd('암호화 시간'); await User.create({ email, nick, password: hash, }); return res.redirect('/'); } catch (error) { console.error(error); next(error); } }) models/user.js도 이렇게 설정이 되어있습니다. // 사용자 테이블 module.exports = ( (sequelize, DataTypes) => ( sequelize.define('user', { email : { type: DataTypes.STRING(40), allowNull: true, unique: true, }, nick : { type: DataTypes.STRING(15), allowNull: false, }, password: { type: DataTypes.STRING(100), allowNull: true, // 카카오 로그인 위해서 true를 해준다. 나중에 데이터베이스 확인할 것. }, // provider는 local과 kakao 구분하기 위해서 provider: { type:DataTypes.STRING(10), allowNull: false, defaultValue: 'local', }, snsID: { type: DataTypes.STRING(30), allowNull: true, } }, { timestamps : true, paranoid : true, }) )); 제대로 적었다고 생각했었는데 User.find 가 없다고 하네요 . 참고로 회원가입할 때 생기는 오류입니다.깃허브 필요하시면 첨부해드릴게요!!
- 미해결Node.js 교과서 - 기본부터 프로젝트 실습까지
코드에 대한질문
passport.authenticate('local', (authError, user, info) => { if(authError) { console.error(authError); return next(authError); } if (!user) { req.flash('loginError', info.message); return res.redirect('/'); } return req.login(user, (loginError) => { // 혹시나, 로그인에서 실패할 경우 에러 점검한다. if (loginError) { console.error(loginError); return next(loginError); } return res.redirect('/'); }); })(req, res, next); 제일 밑에 있는 (req, res, next)를 다시 적어주는 이유는 바로 실행해주기 위한 조건입니까?
- 미해결Node.js 교과서 - 기본부터 프로젝트 실습까지
jwt 와 passport-jwt 에 대해서 질문 하나만 드리겠습니다.
안녕하세요. 강의를 쭉 수강하고 나서 , 스스로 어플의 로그인 기능을 구현하려고 고군분투 중입니다. 강의와 직접적인 연관은 없는 부분이라 질문을 드려도 될지 모르겠습니다 ㅠㅠ 보통 모바일 어플의 경우 어플이 종료되거나 기기가 꺼지더라도 항상 로그인 상태가 유지 중인데, 그것을 세션이 아닌 jwt 로 구현한다는 것을 알았습니다. 강의 중에 sign() 메서드로 jwt 발급과 verify() 메서드로 검증하는 방법을 배웠는데, 구글에서 passport-jwt 를 사용하라는 글을 봤습니다. 제가 궁금한 것은, 최초의 로그인 후 sign() 메서드로 jwt를 발급하고, 그 발급된 jwt 를 클라이언트의 앱에 심는다고 한다면, 그 이후로 verify()를 통해 심어진 jwt를 검증하면 이 사용자가 허가된 user 인지 아닌지 알 수 있지 않나요? passport-jwt 를 사용해야하는 이유가 혹시 뭔가 있을까요? {session : false } 라는 option 때문에 사용하라고 하는 것인지... 제가 무언가를 잘못 생각하고 있는건지ㅠㅠ... 수업과 직접적인 연관은 없지만 코멘트 남겨주시면 감사하겠습니다!!
- 미해결Node.js 교과서 - 기본부터 프로젝트 실습까지
혼자해보기는 정답이 없는건가요??
깃허브에있는 코드가 정답이아니라 스스로 해보라는것인가요??혹시 완성되있는코드는 따로 없을가요 다른사람이 해본것과 비교해보고싶은데
- 해결됨Node.js 교과서 - 기본부터 프로젝트 실습까지
request 작성
https://developers.kakao.com/docs/restapi/tool#user-api#/v1/user/unlink 저 곳 설명에 의하면 https://kapi.kakao.com/v1/user/unlink 로 헤더에 Authorization: Bearer 4S4XZfAsIZ1RFqr9bwWc2N0-qK-lW3ocUMIZUQorDKYAAAFugtugRw 내용을 담아 request요청을 보내라고 하여 if (req.user.dataValues.provider == 'kakao'){ let option = { uri: 'http://kapi.kakao.com/v1/user/unlink', method: 'POST', headers: `Authorization: Bearer ${req.user.dataValues.token}`, } requset(option, (error, respons, body) => { if (error){ console.error(error); return next(error); } else { console.log("카톡 리퀘스트로 됨!!"); req.logout(); req.session.destroy(); res.redirect('/'); } }); } else{ console.log("logout OK"+req.user.dataValues.token); req.logout(); req.session.destroy(); res.redirect('/'); } 이렇게 작성했으나 보내지지 않았습니다 ㅠㅠ 혹시 request에 헤더를 넣어 보내는 법을 알려주실 수 있나요?
- 해결됨Node.js 교과서 - 기본부터 프로젝트 실습까지
카카오톡 로그아웃 안됨.
router.get('/logout', isLoggedIn, (req, res) => { req.logout(); req.session.destroy(); res.redirect('/'); }) 라우터에 로그아웃을 잘 작성하였고 세션도 비워주지만 아이디와 비밀번호를 적지 않고 카카오톡 버튼을 눌러도 다른 카카오톡 아이디와 비밀번호를 입력하고 눌러도, 서버를 실행하고 처음 카카오톡 아이디로 로그인한 계정으로 다시 로그인 됩니다. Token이나 login방식에 문제가 있는 것 같은데 어디가 잘못된 것인지 감이 안잡힙니다. https://devtalk.kakao.com/t/node-js-passport/48774 구글 검색 결과 같은 증상으로 카카오톡에 문의한 사람이 있었으나 저 해결책을 보고 무슨 의미인지 이해하지 못했습니다 ㅠㅜ...
- 미해결Node.js 교과서 - 기본부터 프로젝트 실습까지
"crypto.createCipher" 사용시 deprecated (node12)
강사님, 안녕하세요? crypto 부분에서 (책 3.5.5.2 양방향 암호화) 2019년 11월 현재 "crypto.createCipher" 사용시 deprecated 되었다고 경고를 보내주고 있습니다. (node12) "crypto.createCipheriv" 를 사용하라고 나오는데, 사용방법이 궁금합니다. iv 가 이니셜벡터라고 하는데 정확하게 어떤 것인지 잘 모르겠네요 ^^; node 8에서만 createCipher 를 사용해야 할까요? 감사합니다.
- 미해결Node.js 교과서 - 기본부터 프로젝트 실습까지
cookie.sign 관련 질문 하나 드리겠습니다.
안녕하세요!! 강의 잘 듣구있습니다!! Cookie: `connect.sid=${'s%3A' + cookie.sign(req.signedCookies['connect.sid'], process.env.COOKIE_SECRET)}` 헤더에 위와 같은 쿠키를 넣어 보내는 이유가 결국은 "같은 사람이 보냈다는 것을 서버에게 알려주기 위함" 이라고 말씀해주셨는데, 제가 궁금한 것은 그렇다면 결국 최초 localhost:8005 에 접속했을 때, 서버가 보내는 set-cookie 의 값(=express 가 만든 세션 쿠키)과's%3A' + cookie.sign() 이거로 인해 생긴 쿠키의 문자열?이 결과적으론 같다는 것으로 이해했습니다. 실제로 console 로 찍어보니 같게 나오기도 해서 일단 받아들였습니다. 제가 궁금한 것은1. 이 2가지 쿠키가 어떻게 암호화가 과정을 거쳐서 같은 의미를 나타내는 쿠키가 되는지 궁금합니다. 결국 req.sign() 이란 메서드가 서명된 쿠키를 같은 key로 암호화하기 때문에 같아지는 것인지... 2. req.signedCookies['connect.sid'] 는 말 그대로 서명된 쿠키인데, 이 서명된 쿠키를 굳이 왜 또 같은 secret-key 로 암호화하게 되는 것인지 ㅠㅠ... express가 만든 세션 쿠키(req.signedCookies['connect.sid']) --> 클라이언트 ( 한 번 더 암호화?? 엄청 긴 이상한 string) --> 다시 express로 들어올 떄(req.signedCookies['connect.sid']) --> axios 로 보낼 때( sign() 메서드로 아까 클라이언트 보낼 때랑 같은 한 번더 암호화? 된 긴 string) 위와 같은 흐름이 맞는지 궁금합니다. 저 스스로가 잘 이해를 못하고 있어서 질문이 좀 난해한 것 같아서 죄송합니다!! 감사합니다. 콘솔로그 결과는 아래 첨부 해놓겠습니다!! 최초 connection 때의 header : {"host":"localhost:8005","connection":"keep-alive","accept":"*/*","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36","sec-fetch-site":"same-origin","sec-fetch-mode":"cors","referer":"http://localhost:8005/room/5dcbfa3fff28e31ffcb4d4bf?password=","accept-encoding":"gzip, deflate, br","accept-language":"ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7","cookie":"connect.sid=s%3APILsEVhtt485hYWal47Hi5LzVmU9xzMy.uKLfTbFcdOJLpo3id8g9Biw1Dg2EH9F7yWQtJqyOS7k; io=o0yIKhR3KcO_wrVBAAAC"} req.signedCookies['connect.sid'] : PILsEVhtt485hYWal47Hi5LzVmU9xzMy cookie.sign(req.signedCookies['connect.sid'], process.env.COOKIE_SECRET) : PILsEVhtt485hYWal47Hi5LzVmU9xzMy.uKLfTbFcdOJLpo3id8g9Biw1Dg2EH9F7yWQtJqyOS7k axios로 /room/:id/sys 요청할 때 헤더 : {"accept":"application/json, text/plain, */*","content-type":"application/json;charset=utf-8","cookie":"connect.sid=s%3APILsEVhtt485hYWal47Hi5LzVmU9xzMy.uKLfTbFcdOJLpo3id8g9Biw1Dg2EH9F7yWQtJqyOS7k","user-agent":"axios/0.19.0","content-length":"15","host":"localhost:8005","connection":"close"}
- 미해결Node.js 교과서 - 기본부터 프로젝트 실습까지
로컬 로그인시 이런 문제가 발생합니다.
Missing credentials 왜 이런 문제가 발생하는지 모르겠습니다 ㅠ
- 해결됨Node.js 교과서 - 기본부터 프로젝트 실습까지
질문있습니다
https://www.inflearn.com/questions/12695 여기 질문 내용과 중복되어서 링크도 함께 남깁니다. 답변해주신 2번 내용에서 프론트 요청인지, 서버요청 인지에 따라 분기처리해주는게 좋다고 하셨는데, 마지막 대댓글처럼 main.pug에서 ajax요청시에는 프론트요청이고, call서버의 index.js에서 axios요청시에는 서버 요청인건 알겠는데... 이걸 어떻게 구분해서 처리하는건지 잘 모르겠습니다 ㅠㅠ 둘 다 값이 clientSecret에 담겨오는 것 같은데 ... 이 값이 어느 요청인지 구분하는 방법이 무엇인가요? 혹시 req.headers부분으로 구분하는건가요??
- 미해결Node.js 교과서 - 기본부터 프로젝트 실습까지
질문하나만 드리겠습니다.
안녕하세요!! 강의 잘 듣고 있습니다. 다름 아니라 스스로 해보기 해설을 보기 전에 저 스스로 푸려고 고군분투 중인데, chat.on('connection', (socket) => { socket.to(roomId).emit('join', args) }) 이 코드에서, 기존에 시스템 메세지를 프론트로 전달했었습니다. 제가 궁금한 점은 '최초로 방을 만든 사람'이 connection이 될 때는 저 emit 함수가 작동이 안되는지, 채팅창에 최초로 방 만든 사람의 정보가 뜨지 않습니다. (Microsoft Edge 로 다음 사람이 들어올 때는 잘 됩니다!!) 저는 '최초로 방을 만든 사람'이 만든 순간에도 emit 함수를 작동시키고 싶은데 혹시 어떻게 하면 좋을까요?? 감사합니다.
- 해결됨Node.js 교과서 - 기본부터 프로젝트 실습까지
async await
routes/page.js 파일에서 //메인페이지router.get('/', (req, res, next) => { Post.findAll({ include: { model: User, attributes: ['id', 'nick'], }, order: [['createdAt', 'DESC']], }) .then( (posts) => { res.render('main', { title: 'NodeBird', twits: posts, user: req.user, loginError: req.flash('loginError'), }); }) .catch ( (error) => { console.error(error); next(error); });}); 이부분을 async로 바꾸고 싶어서.. router.get('/', async (req, res, next) => { try { const posts = await Post.findAll({ include: { model: User, attributes: ['id', 'nick'], }, order: [['createdAt', 'DESC']], }); res.render('main', { title: 'Nodebird', twits: posts, user: req.user, loginError: req.flash('loginError'), }); } catch (err) { console.error(err); next(err); } }); 이렇게 했는데...맞게 바꾼건가요? await가 붙으면 작업이 끝날 때까지 기다린다는 의미라서 posts에 값이 담길 때까지 기다리고 담긴 후에 render가 실행된다는 의미 맞을까요? 제가 비동기 부분에 대한 이해가 좀 부족한것 같네요 ㅠㅠ =========================================== 아, 그리고 추가적으로 routes/post.js 에서 router.get('/hashtag', async (req, res, next) => { const query = req.query.hashtag; //사용자가 검색하고자 하는 것 if (!query) { //아무것도 입력 안하면 return res.redirect('/');//기본페이지로 } try { const hashtag = await Hashtag.findOne( { where: { title: query }}); let posts = []; if (hashtag) {//찾은 것이 있으면 posts = await hashtag.getPosts({ include: [{ model: User }]});//다대다관계 가져오면서, 사용자까지 넣어서 가져옴 } return res.render('main', { title: `${query} | NodeBird`, user: req.user, twits: posts, }); } catch (error) { console.error(error); next(error); }}); 마지막에 render하시면서 return을 붙이시던데, 특별한 이유가 있으신건가요?