-
비밀 설정 정보 관리Study/Node, React 기초 강의_John Ahn 2023. 2. 19. 00:51
github에 commit 할 때 mongodb의 아이디, 비밀번호를 유출시키지 않기 위하여 dev.js에 따로 mongodb 아이디 비밀번호에 관한 정보를 빼놓은 후. gitignore 파일에 dev.js 파일을 포함시킨다.
dev.js
module.export = { mongoURI: 'mongodb+srv://<아이디>:<비밀번호>@boilerplate.6t2ootw.mongodb.net/?retryWrites=true&w=majority' }
.gitignore
node_modules dev.js
개발 진행 시 Local development 환경에서의 개발과 Deploy(배포) 한 후 개발(production)로 나누어 지는데 prod.js에 Deploy(배포)한 후 mongodb에 연결될 수 있도록 구현하고 dev.js에 Local development 환경에서의 개발할 때 mongodb에 연결될 수 있도록 구현한다.
prod.js
module.exports = { mongoURI: process.env.MONGO_URI }
key.js를 통해 Local development 환경과 Deploy(배포)한 후 개발 환경을 확인하게 하고 그에 맞는 mongodb 연결 방법을 선택한다.
key.js
if (process.env.NODE_ENV === 'production') { module.exports = require('./prod'); } else { module.exports = require('./dev'); }
현재 상태로 npm run을 진행할 시 아래와 같은 error가 발생하였다.
MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
원인은 Heroku 가입하지 않은채 해당코드를 사용해서 발생하였고 오류 해결은 아래의 블로그를 참고하였다.
Node.js와 React로 간단한 웹페이지를 만들어보자 2편
<목차>BodyParser & PostMan & 회원 가입 기능 Nodemon 설치 비밀 설정 정보 관리 Bcrypt로 비밀번호 암호화 하기client와 sever간의 통신을 위해 미리 준비해야할 것들이 있습니다. client는 로그인할 때 정보를
velog.io
나는 배포를 하지 않을 계획이기 때문에 index.js에서 mongodb를 연결하였다.
index.js
// express 모듈을 추가 const express = require('express') // 새로운 express 모듈을 생성 const app = express() // port 설정 const port = 5000 // User 모델을 가져옴 const { User } = require("./models/User"); // bodyPaser를 가져옴 const bodyPaser = require("body-parser"); // config를 가져옴 const config = require('./config/key'); // bodyPaser 옵션주기 // application/s-www-form-urlencoded app.use(bodyPaser.urlencoded({ extended: true })); // application/json app.use(bodyPaser.json()); // mongoose 연결 const mongoose = require('mongoose') // error 발생을 막기 위한 코드 mongoose.connect("mongodb+srv://<아이디>:<비밀번호>@boilerplate.6t2ootw.mongodb.net/?retryWrites=true&w=majority" ).then(() => console.log('MongoDB Connected...')) // DB 연결 확인을 위한 코드 .catch(err => console.log(err)) // Hello World! 전송 app.get('/', (req, res) => { res.send('Hello World!!') }) 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 }) }) }) // 5000번 port에서 실행 app.listen(port, () => { console.log(`Example app listening on port ${port}`) })
'Study > Node, React 기초 강의_John Ahn' 카테고리의 다른 글
로그인 기능 구현 (0) 2023.02.19 Bcrypt를 이용한 비밀번호 암호화 (0) 2023.02.19 Nodemon (0) 2023.02.14 BodyParser & PostMan & 회원 가입 기능 (0) 2023.02.13 SSH를 이용하여 GITHUB 연결 (0) 2023.02.13