무료
다른 수강생들이 자주 물어보는 질문이 궁금하신가요?
- 미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
db connectio 에러
DB 연결에서 계속 오류가 나요 에러 메시지 보고 cmd 창에서 ip 보고 mongoDB network access 에서 ip 수정하고 다시 이전꺼랑 해서 새로 추가했는데 동일하게 오류가 나와요 확인 부탁드립니다 ㅜㅜ PS D:\nodeJs\models> npm run start > nodejs@1.0.0 start D:\nodeJs > node index.js Example app listening at http://localhost:5100 MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/ at NativeConnection.Connection.openUri (D:\nodeJs\node_modules\mongoose\lib\connection.js:846:32) at D:\nodeJs\node_modules\mongoose\lib\index.js:351:10 at D:\nodeJs\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5 at new Promise (<anonymous>) at promiseOrCallback (D:\nodeJs\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10) at Mongoose._promiseOrCallback (D:\nodeJs\node_modules\mongoose\lib\index.js:1149:10) at Mongoose.connect (D:\nodeJs\node_modules\mongoose\lib\index.js:350:20) at Object.<anonymous> (D:\nodeJs\index.js:14:10) at Module._compile (internal/modules/cjs/loader.js:1251:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1272:10) at Module.load (internal/modules/cjs/loader.js:1100:32) at Function.Module._load (internal/modules/cjs/loader.js:962:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) at internal/main/run_main_module.js:17:47 { reason: TopologyDescription { type: 'ReplicaSetNoPrimary', setName: null, maxSetVersion: null, maxElectionId: null, servers: Map(3) { 'wwwpyk-shard-00-01.7lopm.mongodb.net:27017' => [ServerDescription], 'wwwpyk-shard-00-02.7lopm.mongodb.net:27017' => [ServerDescription], 'wwwpyk-shard-00-00.7lopm.mongodb.net:27017' => [ServerDescription] }, stale: false, compatible: true, compatibilityError: null, logicalSessionTimeoutMinutes: null, heartbeatFrequencyMS: 10000, localThresholdMS: 15, commonWireVersion: null } }
- 미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
heroku 배포에 대하여
안녕하세요. 헤로쿠 배포해서 url 까지 받았는데요 url을 열면 localhost:5000번 즉, client 화면이 안나오고 server쪽에서 열리더라고요... 어떻게 해야 할까요??
- 미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
heroku 배포에 관하여
좋은 강의 감사합니다. 강의대로 모든 준비를 마치고 heroku에 배포한 결과 Client는 정상적으로 동작하는데 서버가 정상적으로 동작하지 않는 것 같습니다. 로그인 또는 회원가입을 시도할때 다음과 같은 에러가 발생합니다. 일단 package.json 파일은 다음과 같이 수정했는데 어느 부분을 수정해야 할지 모르겠습니다. 배포를 해야 다음 강의를 진행할텐데 여기서 멈춰있습니다. 바쁘시겠지만 도움 부탁드립니다. 감사합니다. 수정한 부분은 다음과 같습니다. "scripts": { "start": "concurrently \"npm run server\" \"npm run client\"", "server": "node server/index.js", "client": "cd client && npm start", "test": "echo \"Error: no test specified\" && exit 1", "heroku-postbuild": "cd client && npm install && npm run build" }, const port = process.env.PORT || 5000; app.listen(port, () => console.log(`Example app listening on port ${port}!`));
- 해결됨따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
TypeError: user.comparePassword is not a function 라고 에러메시지가 뜹니다..
현재 토큰생성 with jsonwebtoken 들으면서 진행중에 있는데요. 여기서 TypeError: user.comparePassword is not a function 라고 뜨면서 postman이 작동하지 않고있습니다.. 무슨이유일까요 // Login Route 생성 app.post('/login', (req, res) => { // 요청된 이메일을 데이터베이스 안에서 있는지 찾는다 User.findOne({ email: req.body.email }, (err, user) => { if(!user) { return res.json({ loginSuccess: false, message: "제공된 이메일에 해당되는 유저가 없습니다." }) } // 요청된 이메일이 데이터 베이스에 있다면 비밀번호가 맞는건지 확인한다 user.comparePassword(req.body.password, (err, isMatch) => { if(!isMatch) return res.json({ loginSuccess: false, message: "비밀번호가 틀렸습니다." }) // 비밀번호까지 맞다면 토큰을 생성한다. user.generateToken((err, user) => { if(err) return res.status(400).send(err); // 쿠키에 토큰을 저장한다. res.cookie("x_auth", user.token) .status(200) .json({ loginSuccess: true, userId: user._id }) }) }) }) })
- 미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
7강에서 오류가 떠요
postman에서 이름,패스워드를 json형식으로 쓰고 send를 누르면 success가 나오지 않고 아래처럼 나와요ㅜㅜ 어디가 잘못된 걸 까요 {"success":false,"err":{"driver":true,"name":"MongoError","index":0,"code":11000,"keyPattern":{"email":1},"keyValue":{"email":null}}}
- 미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
npm run start
이렇게 에러가 뜨는데 뭐가 문제 일까요?? ㅜ 제발 도와주세요 package.json에 start 부분은 확실하게 있고 다른 비슷한 오류에 솔루션 주신 <package.json 파일이 명령어를 입력하시는 디렉토리 내에 없고 다른곳에 있다> 라는 말이 무슨뜻인 지 모르겠습니다..!
- 미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
User.js 안에서 var user = this; 에 대한 궁금증
userSchema.pre("save", function (next) { var user = this; //user == userSchema if (user.isModified("password")) { //model 속 field 안에 'password'가 바뀔때만. //비밀번호를 암호화 시킨다. bcrypt.genSalt(saltRounds, function (err, salt) { if (err) return next(err); //next 하면 index.js user.save function으로 바로 넘어간다. bcrypt.hash(user.password, salt, function (err, hash) { //hash == 암호화된 비밀번호 //user.password ==> plainPassword if (err) return next(err); user.password = hash; next(); }); }); } }); userSchema.pre("save", function (next) { var user = this; } 이 부분에 대한 궁금증입니다. 하단에 user.password =hash로 쓰기위해 var user = this; 를 쓴다는것을 그냥 보면 알겠는데, 제 머릿속에서는 var user = this.userSchema라고 선언을 해야 user에 userSchema가 담길것같은데 그냥 this;로 진행해도 실행이 되서 좀 의아해서 질문글을 올립니다.
- 미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
{}로 둘러싸인 변수명
JS의 기본적인 문법을 숙지하고 해당 강의를 수강 중입니다. 해당 수업의 코드에 const {User} = require('./~');라는 코드가 있습니다. JS변수에 대해 배울 때 변수 선언 시 {}로 변수명을 둘러싸는 것을 본 적이 없어서 어떻게 이해하면 될지 궁금하여 질문드립니다.
- 미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
윈도우에서 nodemon 실행 안되시는 분
VScode 에서 터미널은 기본값이 powershell 로 되어 있습니다. 이 터미널을 cmd 로 바꿔주시면 정상적으로 작동합니다. 아마 powershell 에서 경로나 권한 이슈가 있는 모양입니다.
- 미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
mongoose.connect 질문
user 부분 쪽에 오류 표시가 뜨는데 이유가 뭘까요? 그리고 저 상태로 로컬호스트에 연결하여 띄우면 콘솔창에 아무내용이 뜨지 않습니다 ㅠㅠ
- 해결됨따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
[/api/users/logout] 에러 질문: Cannot read property 'x_auth' of undefined
안녕하세요 logout 기능을 구현했는데 아래 에러가 떠서 너무 힘들어서 질문드립니다. postman으로 POST 메소드로 login에 성공하였고, 토큰이 생기는것을 확인했습니다. 그 후 바로 postman으로 GET 메소드로 /api/users/logout을 하려 하는데 아래와 같은 에러가 발생하네요 ㅠㅠ 제 깃헙 주소에서 전체코드를 보실 수 있습니다. https://github.com/kth990303/boiler-plate-prac 어디가 문제인지 잘 모르겠네요. 답변 부탁드립니다 ㅜㅜ 감사합니다. TypeError: Cannot read property 'x_auth' of undefined at auth (C:\Users\User\Desktop\web_workspace\boiler_plate\middleware\auth.js:6:29) at Layer.handle [as handle_request] (C:\Users\User\Desktop\web_workspace\boiler_plate\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\User\Desktop\web_workspace\boiler_plate\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (C:\Users\User\Desktop\web_workspace\boiler_plate\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\Users\User\Desktop\web_workspace\boiler_plate\node_modules\express\lib\router\layer.js:95:5) at C:\Users\User\Desktop\web_workspace\boiler_plate\node_modules\express\lib\router\index.js:281:22 at Function.process_params (C:\Users\User\Desktop\web_workspace\boiler_plate\node_modules\express\lib\router\index.js:335:12) at next (C:\Users\User\Desktop\web_workspace\boiler_plate\node_modules\express\lib\router\index.js:275:10) at C:\Users\User\Desktop\web_workspace\boiler_plate\node_modules\body-parser\lib\read.js:130:5 at invokeCallback (C:\Users\User\Desktop\web_workspace\boiler_plate\node_modules\raw-body\index.js:224:16) at done (C:\Users\User\Desktop\web_workspace\boiler_plate\node_modules\raw-body\index.js:213:7) at IncomingMessage.onEnd (C:\Users\User\Desktop\web_workspace\boiler_plate\node_modules\raw-body\index.js:273:7) at IncomingMessage.emit (events.js:327:22) at endReadableNT (internal/streams/readable.js:1327:12) at processTicksAndRejections (internal/process/task_queues.js:80:21) 코드는 아래와 같습니다. Auth.js (auth.js:6:29는 const token=req.cookies.x_auth 부분입니다.) const { User } = require("../models/User"); const auth=(req, res, next)=>{ // 인증처리 // client cookie에서 토큰 가져오기 const token=req.cookies.x_auth; // token을 jwt로 decoding User.findByToken(token, (err, user)=>{ if(err) throw err; if(!user){ return res.json({ isAuth: false, error: true }); } req.token=token; req.user=user; next(); }) } module.exports={auth}; User.js (Token 생성, findByToken function 부분) userSchema.methods.generateToken=function(cb){ const user=this; const token=jwt.sign(user._id.toHexString(), 'secretToken'); user.token=token; user.save(function(err, user){ if(err) return cb(err); cb(null, user); }); } userSchema.statics.findByToken=function(token, cb){ const user=this; jwt.verify(token, 'secretToken', function(err, decoded){ user.findOne({"_id": decoded, "token": token}, function(err, user){ if(err) return cb(err); cb(null, user); }); }); } const User=mongoose.model('User', userSchema); // 다른 파일에서도 이 모델을 쓸 수 있도록 module.exports={ User } Index.js (/api/users/login, /api/users/auth, /api/users/logout) app.post('/api/users/login', (req, res)=>{ // 요청된 이메일을 db에서 찾는다. User.findOne({email: req.body.email}, (err, user)=>{ if(!user){ return res.json({ loginSuccess: false, message: "Unvalid email" }); } // 요청된 이메일이 db에 있다면 비밀번호 일치여부 확인 user.comparePassword(req.body.password, (err, isMatch)=>{ if(!isMatch) return res.json({ loginSuccess:false, message:"Wrong password" }); // 일치 시, 토큰 생성 user.generateToken((err, user)=>{ if(err) return res.status(400).send(err); // 토큰을 쿠키에 저장 res.cookie("x_auth", user.token) .status(200) .json({ loginSuccess: true, userId: user._id }); }); }); }); }); // auth라는 미들웨어를 추가 // request를 받으면 call back function 호출 전에 middleware실행 app.get('/api/users/auth', auth, (req, res)=>{ res.status(200).json({ _id: req.user._id, isAdmin: req.user.role===0?false:true, isAuth: true, email: req.user.email, name: req.user.name, lastname: req.user.lastname, role: req.user.role, image: req.user.image }); }); app.get('/api/users/logout', auth, (req, res)=>{ console.log(req.user); user.findOneAndUpdate({_id:req.user._id}, { token: "" }, (err, user)=>{ if(err) return res.json({ success: false, err }); return res.status(200).send({ success: true }) }) }) 아래는 postman 화면 결과입니다. +) 전체적으로 수업시간의 코드는 이해가 되는데, 어떤 의식의 흐름으로 이렇게 작성하는지 신기할 때가 많습니다. 예를 들면 쿠키에서 토큰을 가져온다 할 때 let token=req.cookies.x_auth 에서 req에 cookies에서 쿠키 이름인 x_auth로 접근하면 바로 토큰이 나온다는 사실을 몰랐음. 이런 경우는 어떤 부분을 공부해야 할까요? 전체적으로 자바스크립트 실력이 붕 뜬 느낌입니다. (초보자라 질문이 좀 이상한 것 같기도 하네요...)
- 미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
Request failed with status code 404 문제 ㅜ 도와주세요
{ "message": "Request failed with status code 404", "name": "Error", "stack": "Error: Request failed with status code 404\n at createError (http://localhost:3000/static/js/vendors~main.chunk.js:1142:15)\n at settle (http://localhost:3000/static/js/vendors~main.chunk.js:1376:12)\n at XMLHttpRequest.handleLoad (http://localhost:3000/static/js/vendors~main.chunk.js:616:7)", "config": { "url": "/api/users/register", "method": "post", "data": "{\"email\":\"123123@gmail.com\",\"password\":\"123123\",\"name\":\"dan\"}", "headers": { "Accept": "application/json, text/plain, */*", "Content-Type": "application/json;charset=utf-8" }, "transformRequest": [ null ], "transformResponse": [ null ], "timeout": 0, "xsrfCookieName": "XSRF-TOKEN", "xsrfHeaderName": "X-XSRF-TOKEN", "maxContentLength": -1, "maxBodyLength": -1 } } 로그인, 회원가입까지 만들어봤는데 둘다 안되네요. 페이지를 찾을수 없는걸로 나오는데 문제가 무엇일까요. /api/users/login/api/users/register 오타 문제도 아닌것같고.... 혼자 찾아보려다가 답이 안보여서 도움 요청합니다 ㅜㅜ 깃헙 주소도 같이 남길께요 . https://github.com/WanzGoh/Node.js_boiler-plate 감사합니다.
- 미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
port 번호 관련 질문
안녕하세요 선생님~ 항상 강의 잘듣고 있습니다. 다름이 아니라 강의 수강 중 궁금한 점이 생겨 질문 남깁니다. 맨처음에 서버 포트 설정시 아무거나 해도 된다고 하셔서 저는 3000번을 포트로 설정했었는데요. 클라이언트의 경우 따로 설정한게 없는 것 같은데 기본 포트가 3000번인지 궁금합니다. 현재 저는 클라이언트와 백엔드 서버를 켜면 이미 같은 포트에 somethins is running 이라고 뜹니다.
- 미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
postman 무한 로딩 문제ㅜ
안녕하세요 로그인 과정에서 잘못된게 없어보이는데 무한로딩이 계속 됩니다. 어떤게 문제일까요. 도움 부탁드립니다. ㅜㅜ 아래 깃허브 주소남겼습니다. ㅜ https://github.com/WanzGoh/Node.js_boiler-plate
- 미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
오류확인 부탁드립니다.
const express = require('express') const app = express() const bodyParser = require('body-parser'); const port = 5000; const { User } = require("./models/User"); //application/x-www-form-urlencoded app.use(express.urlencoded({ extended: true })); //application/json app.use(express.json()); const mongoose = require('mongoose') mongoose.connect("mongodb+srv://jaesoek:1234@cluster0.qwtf5.mongodb.net/myFirstDatabase?retryWrites=true&w=majority", { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false }).then(() => console.log('MongoDB Connected...')) .catch(err => console.log(err)) app.get('/', (req, res) => res.send('Hello World!~~ ')) app.get('/api/hello', (req, res) => res.send('Hello World!~~ ')) app.post('/api/users/register', (req, res) => { //회원 가입 할떄 필요한 정보들을 client에서 가져오면 //그것들을 데이터 베이스에 넣어준다. const user = new User(req.body) user.save((err, userInfo) => { if (err) return res.json({ success: false, err }) return res.status(200).json({ success: true }) }) }) app.listen(port, () => console.log('server on..')) 위에 처럼 코드를 적고 포스트맨에서 보내면, 계속 이렇게 뜨네요 port번호를 바꿔보기도 했는데 안됩니다 ㅠ
- 미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
로그인 및 서버-클라이언트 데이터 전달 오류
안녕하세요! 강의 잘 듣고 있습니다 :) 이번 강의를 들으면서 따라쳤는데 아래와 같은 오류가 발생하면서 로그인이 안됩니다. user_action에서 경로 /api/users/login 또는 http://localhost:5000/api/users/login 로도 시도해보고 LoginPage에서 import { withRouter } from 'react-router-dom'; export default withRouter(LoginPage)도 해봤는데 계속 이런 오류가 뜹니다. 물론 로그아웃도 안됩니다ㅠㅠ
- 미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
도와주세요 ㅠ
로그인 라우터까지 만들었을 때는 정상적으로 됬었는데 로그아웃 라우터 만들고 해보니까 위에처럼 나오네요. 오타는 없는거같은데... 한번 봐주실수있나요? unibook1283/boiler-plate (github.com)
- 미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
client start오류(실행 안됨)
삭제된 글입니다
- 미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
카카오 로그인 구현을 완료했는데 여기에도 인증을 추가할 수 있는 방법이 있을까요?
안녕하세요 현재 진행하고 있는 프로젝트에서 로그인, 로그아웃, 회원가입, 인증 기능을 추가하기 위해 선생님의 강의를 들으며 구현을 완료했습니다. 그리고 카카오 로그인 기능을 추가했는데 문제는 카카오 로그인시 로그인 인증이 되지 않아 로그인했을 경우에만 들어갈 수 있는 페이지에 들어갈 수 없다는 것입니다. 밑에는 카카오 로그인 구현 코드이고 제 생각에는 /hoc/auth.js 파일에 무언가 추가해 줘야겠다 싶은데 어떻게 하면 좋을까요? const [isLogin, setIsLogin] = useState(false); const loginWithKakao = () => { try { return new Promise((resolve, reject) => { if (!Kakao) { reject("Kakao 인스턴스가 존재하지 않습니다."); } Kakao.Auth.login({ success: (res) => { localStorage.setItem("token", res.token); setIsLogin(true); props.history.push("/"); }, fail: (err) => { console.error(err); }, }); }); } catch (err) { console.error(err); } }; const logoutWithKakao = () => { if (Kakao.Auth.getAccessToken()) { console.log( "카카오 인증 액세스 토큰이 존재합니다.", Kakao.Auth.getAccessToken() ); Kakao.Auth.logout(() => { console.log("로그아웃되었습니다.", Kakao.Auth.getAccessToken()); setIsLogin(false); localStorage.clear(); props.history.push("/login"); }); } };
- 미해결따라하며 배우는 노드, 리액트 시리즈 - 기본 강의
포스트맨 오류 질문
안녕하세요 강의 너무 잘 듣고있습니다. 포스트맨에서 post 하면 false가 뜨네요. err에 아무것도 뜨지 않아 추측이 어렵습니다 도와주세요! (connect 는 은 숨기느라 ~~표시입니다) const express = require('express') const app = express(); const port = 5000; const bodyParser = require("body-parser"); const { User } = require("./models/User"); //application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: true })); //application/json app.use(bodyParser.json()); const mongoose = require('mongoose'); //application ~ mongoDB mongoose .connect('mongodb+srv://~~~~~~~~', { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false }) .then(() => console.log('MongoDB Connected...')) .catch(err => console.log(err)); app.get('/', (req, res) => { res.send('Hello World!😁') }) // [register route] app.post('/register', (req, res) => { // 회원가입에 필요한 정보를 client에서 가져온다. // 그것들을 데이터 베이스에 넣어준다. const user = new User(req.body); user.save((err, userInfo) => { if(err) return res.json({ success: false, err }) return res.status(200).json({ success: true }) }) }) app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`) )