Express JS란?
작업 폴더에 들어가서
> npm init
> npm install express --save
node.js를 설치하고 Express.js를 설치하자
폴더에 index.js 파일을 만든 뒤에
const express = require("express");
const app = express();
const port = 3000;
app.get('/', (req, res) => res.send("Hello, World!"));
app.listen(port, () => console.log(`Example app listenging on port ${port}!`));
package.json에서 "scripts"부분에다가 "start" : "node index.js", 를 추가하자!
그럼 터미널에> npm run start 를 입력했을 때 node index.js 를 입력한 것처럼 되어서 포트가 실행된다.
변경사항을 확인하려면 서버를 죽이고 다시 켜야한다.
몽고DB 연결하기
클러스터를 생성하기 위해
www.mongodb.com 에 접속해 AWS > Singapore > M0 Sandbox 를 선택한다음 Create Cluster를 눌러 Cluster를 생성한다. 이후 Connect를 눌러 Create a MongoDB user에서 Username과 Password를 지정한다.
Choose a connection method > Connect Your Application > Connectino String only부분을 copy해서
const mongoose = require('mongoose');
mongoose.connect("-------")
위 connect의 매개변수에 넣는다.
이 부분에서 <password>부분을 지우고 패스워드를 입력해준다.
Mongoose란? : MongoDB를 편하게 쓸 수 있게 하는 툴이라고 한다.
이렇게 되면 연결 성공!
User 모델 만들기
Model을 만들기 위해서 Schema를 만들자.
https://backend-intro.vlpt.us/2/03.html
2-3. 데이터베이스 스키마와 모델 · GitBook
2-3. 데이터베이스 스키마와 모델 2장의 서론에서는, MongoDB 는 고정적인 스키마를 갖지 않고 있다고 설명을 했습니다. 그런데 이번에 스키마를 미리 만든다니, 조금 헷갈리기도 하지요? 여기서 만
backend-intro.vlpt.us
const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
name: {
type: String,
maxlength: 50,
},
email: {
type: String,
trim: true, // String에서 space부분을 없애준다.
unique: 1, // 중복 방지
},
password: {
type: String,
minlength: 5,
},
lastname: {
type: String,
maxlength: 50,
},
role: {
type: Number,
default: 0,
},
image: String,
token: {
// 유효성 관리
type: String,
},
tokenExp: {
type: Number,
},
});
const User = mongoose.model("User", userSchema);
// 모듈의 사용성을 늘리기 위해 exports
module.exports = { User };
GIT 설치하기
vscode에 terminal에서 작업한다.
>git init
깃 저장소 만들기
>git status
현재 깃에 올라가는 파일들 서치하기
> git add
Working Directory에서 Staging Area로 파일들을 넘기고,
> git commit
Staging Area에서 Git Repository(로컬)로 파일들을 커밋한다
> git push
원격 Git Repository로 파일을 올린다.
SSH로 Github 연결하기
SSH를 생성해서 나의 깃허브에 등록한 다음,
> git remote add origin <github repository 링크>
명령어로 github repository와 연결한다.
>git branch -M main
으로 브랜치를 만들고,
> git push -u origin main
명령어로 git push를 진행한다.
Body-Parser Dependency : 데이터를 분석(Parse)해서 req.body로 출력하는 것
> npm install body-parser --save
회원가입을 위한 라우터 만들기
라우터 : 하나의 서버를 말하는 듯?
const express = require("express"); // express 모듈 가져오기
const app = express(); // express의 function을 이용해 app을 만들기
const port = 5000; // 포트를 지정해서 백 서버 생성
const bodyParser = require("body-parser");
//body-parser에 옵션 주기
app.use(bodyParser.urlencoded({ extended: true })); // application/x-www-form-urlencoded의 형태 데이터를 분석해서 디비에 넣게
app.use(bodyParser.json()); // application/json 형태의 데이터를 분석해서 디비에 넣게
const { User } = require("./models/User");
//User 정보 가져와서 인스턴스 만들기
const mongoose = require("mongoose");
mongoose
.connect(
"mongodb+srv://gyeomi:<password>@testcluster.2znuo.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!!!!!"));
// postman
app.post("/register", (req, res) => {
//회원가입할 때 필요한 정보들을 client에서 가져오면, 그것들을 데이터 베이스에 넣는다.
const user = new User(req.body); //bodyParser를 이용해서 req에 데이터를 넣게 해준다.
user.save((err, userInfo) => {
if (err) return res.json({ success: false, err });
return res.status(200).json({
success: true,
});
}); //몽고DB에서 오는 메소드(user모델에 데이터를 저장시킴)
});
/*
'/register'은 라우터의 end point라고 한다.
*/
app.listen(port, () => console.log(`Example app listening on port ${port}!`)); // 5000의 포트로 app을 실행시킴
Nodemon : Node를 실행할 때 서버를 내리거나 올리지 않고도 소스의 변화를 감지해 서버에 반영한다.
> npm install nodemon --save-dev
start를 이용해서 node index.js를 했었지만, 이제 nodemon index.js를 실행하도록 한다.
> npm run backend
이 방법을 통해 represh만으로 변경사항을 페이지에서 확인할 수 있다.
- index.js에 포함된 mongoose.connect 부분의 인자에 패스워드가 포함된 문구를 git에서 제외하는 방법
local, product에서 작업하는 두가지 경우를 나누어
다음과 같이 config 폴더를 만든뒤 dev.js에는(local 에서 작업하는 경우)
module.exports = {
mongoURI:
"mongodb+srv://gyeomi:<password>@testcluster.2znuo.mongodb.net/myFirstDatabase?retryWrites=true&w=majority",
};
배포하여 작업하는 경우인 prod.js에는
module.exports = {
mongoURL: process.env.MONGO_URI,
};
이렇게 작업한다.
이 두 파일을 연결시킬 key.js에는
if (process.env.NODE_ENV === "production") {
module.exports = require("./prod");
} else {
module.exports = require("./dev");
}
이렇게 써주고 index.js에
const config = require("config/key.js"); 로 export된 모듈을 불러와 작업환경에 맞는 js파일을 index.js에 포함시키게 한다. 그리고 원래 moongose.connect()의 인자에 들어갔던 부분에는 moongose.connect(config.mongoURI)를 넣어서 디비에 연결해준다.
+ node.js에서 const {User} 처럼 중괄호를 써서 모듈을 불러오는 것은 다음 링크에서 확인할 수 있다.
https://ko.javascript.info/destructuring-assignment
구조 분해 할당
ko.javascript.info
bcrypt를 다운받아서 입력받은 비밀번호를 암호화하도록 해보자.
https://www.npmjs.com/package/bcrypt
bcrypt
A bcrypt library for NodeJS.
www.npmjs.com
여기서 참고!
saltRound 지정 -> salt를 생성하고 -> 생성된 salt로 비밀번호를 암호화한다.
userSchema.pre("save", function (next) {
// 비밀번호를 암호화 시킨다.
var user = this; // user은 User 스키마를 가리킴
// 다른 요소가 아닌 password가 변경되었을 때만 비밀번호가 암호화되어 저장되도록 한다.
if (user.isModified("password")) {
bcrypt.genSalt(saltRounds.toExponential, function (err, salt) {
if (err) return next(err); // next로 이동하면 바로 save함수가 실행
// salt가 잘 생성되면 아래 문구가 실행
bcrypt.hash(user.password, salt, function (err, hash) {
if (err) return next(err);
user.password = hash;
next(); // save로 돌아가기
});
//user.password : user 스키마의 plain password(가공되지 않은 비밀번호)
// salt : 생성된 salt
// hash : 암호화된 비밀번호
});
}
});
// user정보를 저장하기 전에 function을 실행하게끔
index.js의 save 메소드를 실행하기 전에, User.js에 userSchema.pre 메소드를 사용해 해당 function 매개변수를 먼저 실행하도록 한다.
password를 변경하였을 경우, bcrypt 내부에 genSalt 메소드로 Salt를 생성한 뒤 이 Salt에서 hash로 password를 변경한다.
- Salt : 함수의 추가 입력으로 사용되는 랜덤 데이터
- Hash : 문자열을 암호화 하는 과정, 해시된 값은 비밀번호 + 솔트값으로 이루어져 있다.
에러 해결
TypeError: Number.prototype.toExponential requires that 'this' be a Number at toExponential (<anonymous>)
코드에서 Exponentioal 메소드를 제거해서 해결
'Framework > Node.js' 카테고리의 다른 글
생활코딩 Node.js 25장-end (0) | 2021.07.22 |
---|---|
생활코딩 Node.js 1~24강 내용 정리 (0) | 2021.07.20 |