인프런 영문 브랜드 로고
인프런 영문 브랜드 로고

인프런 커뮤니티 질문&답변

정수민님의 프로필 이미지
정수민

작성한 질문수

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

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

req is not defined.

작성

·

2.2K

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 }

답변 1

0

John Ahn님의 프로필 이미지
John Ahn
지식공유자

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

정수민님의 프로필 이미지
정수민

작성한 질문수

질문하기