inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

따라하며 배우는 노드, 리액트 시리즈 - 기본 강의

노드 리액트 기초 강의 #10 Bcrypt로 비밀번호 암호화 하기

req is not defined.

2312

정수민

작성한 질문수 6

0

수업 정말 잘 듣고 있습니다 :) 양질의 강의 감사드려요.

질문게시판에 있는 거도 다 참고했는데 Postman에 넣어보니

{
    "success"false,
    "err": {}

}

err의 빈칸이 안없어지네요 ㅠㅠ Users.js 코드를 첨부합니다.

+  console.log("req.body:", req.body)을 해보니 

ReferenceError: req is not defined

이렇게 뜨네요. req 정의가 안 됐다고하여, index.js코드도 첨부합니다.

const express = require('express')
const app = express()
const port = 1004
const bodyParser = require('body-parser');
const config = require('./config/key');

const { User } = require("./models/Users");
//application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: true}));

//application/json
app.use(bodyParser.json());

const mongoose = require('mongoose')
mongoose.connect(config.mongoURI, {
    useNewUrlParser: trueuseUnifiedTopology: trueuseCreateIndex: trueuseFindAndModify: false
}).then(()=>console.log('MongoDB connected...')).catch(err => console.log(err))

app.get('/', (reqres=> res.send('Hello World! nodemon을 적용해써요><'))


app.post('/register', (reqres=> {

    //회원가입할 때 필요한 정보들을 client에서 가져오면
    //그것들을 데이터 베이스에 넣어준다.
    
    const user = new User(req.body)
    //bodyparser가 있기에 가능한 것.

    //bcrypt로 암호화하기
    user.save((err,userInfo)=> {
        if (errreturn res.json({success: falseerr})
        return res.status(200).json({
            success: true
        })
    })
})
//save는 몽고DB에서 온 method



app.listen(port, () => console.log('Example app listening on port ${port}!'))




//0710: req가 정의가 안됐대
//console.log("req.body:", req.body)
--------------------------------------------
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const saltRounds = 10

const userSchema = mongoose.Schema({
    name: {
        type: String,
        maxlength: 50
    },
    email: {
        type: String,
        trim: true,
        unique: 1
    },
    password: {
        type: String,
        maxlength: 50
    },
    role: {
        type: Number,
        default: 0
    },
    image: String,

    token: {
        type: String
    },
    tokenExp: {
        type: Number
    }
})

userSchema.pre('save'functionnext ){
    var user = this;
    //비밀번호를 암호화 시킨다.
    if(user.insModified('password')) {
        bcrypt.genSalt(saltRoundsfunction(errsalt) {
            if(errreturn next(err)
    
            bcrypt.hash(user.passwordsaltfunction(errhash) {
                if (errreturn next(err)
                user.password = hash
                next()
            })
        })
    } else{
        next()
    }
})
// mongoose에서 가져온거, 저장하기 전에 적용할 함수

const User = mongoose.model('User'userSchema)

module.exports = { User }

nodejs react

답변 1

0

John Ahn

현재    클라이언트 ( postman)에서 요청을 보낼떄   console.log(req) 를 했는데 값이 안왔다면 req 를 못받는다면 ..아마 
소스 문제보다는 환경문제일수가 있는것 같은데 혹시   노드가 잘 켜져있나요 ?

깃 이메일이랑 비번이 필요하다고 하네요

0

34

1

404 에러

0

101

1

34강 인증 체크에서 element 사용 때문에 에러나시는 분들 이렇게 하심 됩니다.

0

118

1

로그인, 로그아웃, 토근 작동 안 함

0

238

0

9강 오류 어떻게 해결하나요?

0

193

1

localhost 에서 연결을 거부했습니다.

0

1925

4

포스트맨에서 true가 안떠요

0

150

1

왜 안되나요

0

128

1

몽고db 연결 오류가 납니다 위에껀 입력한 코드, 아래껀 터미널이에요

0

243

1

로그아웃 401 에러(Unauthorized)

0

503

2

암호가 해싱되지 않고 입력값 그대로 db에 저장되는 문제

0

148

1

7강중에서

0

162

2

User.findByToken is not a function

0

210

1

루트 디렉토리

0

269

1

useState

0

560

1

프록시 잘 설정했는데도 404 오류 뜨는 분들

5

874

6

webpack 관련 에러 질문

0

218

1

리액트 관련 질문

0

271

1

14강 로그아웃 안됨

0

318

1

mongoDB 데이터 확인하는 법

0

408

1

postman 에러

0

291

1

선생님 리덕스를 사용하면 어떠한 부분이 좋은지 알 수 있을까요?

0

233

1

다음과 같은 에러들이 발생합니다.

0

272

1

14강 로그아웃 기능 구현시 postman에서 Cannot POST 오류가 뜹니다.

0

379

1