npm
- Node Package Manager
- Node.js에서 사용하는 모듈을 패키지로 만들어 npm에서 관리, 배포
npm 패키지 생성
npm init
- package.json: npm을 통해 설치된 패키지 목록을 관리하고 프로젝트의 정보 및 기타 실행 스크립트를 작성하는 파일
{
"name": "boiler-plate",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"backend": "nodemon index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "jaja",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.0",
"express": "^4.18.1",
"mongoose": "^6.4.5"
},
"devDependencies": {
"nodemon": "^2.0.19"
}
}
express
- 웹 및 모바일 애플리케이션을 위한 일련의 강력한 기능을 제공하는 간결하고 유연한 Node.js 웹 애플리케이션 프레임워크
- 설정
const express = require('express')
const app = express()
const port = 5000 // localhost:[port]
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Hello world 예제
https://expressjs.com/ko/starter/hello-world.html
Express "Hello World" 예제
Hello world 예제 기본적으로 이 앱은 여러분이 작성할 수 있는 가장 간단한 Express 앱일 것입니다. 이 앱은 하나의 파일로 된 앱이며 Express 생성기를 통해 얻게 되는 앱과는 같지 않습니다. (이 예제
expressjs.com
npm install
https://c17an.netlify.app/blog/node.js/npm-install-%EC%A0%95%EB%A6%AC/article/
찬미니즘
배움과 도전을 즐기는 공대생의 기록입니다.
c17an.netlify.app
mongoDB
- 크로스 플랫폼 도큐먼트 지향 데이터베이스 시스템
- NoSQL, JSON과 같은 동적 스키마형 도큐먼트들을 선호
cluster 생성
- free 선택
- Connect에서 IP 설정과 User 생성
- 생성된 URI를 server에 이용

mongoose
- 몽고DB와 Express.js 웹 애플리케이션 프레임워크 간 연결을 생성하는 자바스크립트 객체 지향 프로그래밍 라이브러리
- 몽고DB를 편하게 쓸 수 있는 Object Modeling Tool
Mongoose ODM v6.4.6
Let's face it, writing MongoDB validation, casting and business logic boilerplate is a drag. That's why we wrote Mongoose. const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/test'); const Cat = mongoose.model('Cat', { name:
mongoosejs.com
npm install mongoose
const mongoose = require('mongoose')// mogoose: nodejs와 mongoDB 연결하는 ODM
mongoose.connect(config.mongoURI)// mongoDB URI를 이용하여 연결
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err))
- schema 생성(table과 비슷한 개념)
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({// schema == table 선언
name: {
type: String,
maxlength: 50
},
email: {
type: String,
trim: true,
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)
module.exports = { User }
const { User } = require("./models/User");
app.post('/register', (req, res) => {
// 회원가입 할 때 필요한 정보들을 client에서 가져오면
// 그것들을 데이터베이스에 저장
const user = new User(req.body);
user.save((err, userInfo) => { // save()로 저장
if(err) return res.json({success: false, err});
return res.status(200).json({
success: true
});
});
})
body-parser
- body 데이터를 분석(parsing)하여 req.body로 출력
npm install body-parser
const bodyParser = require('body-parser');
//application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: true}));
//application/json
app.use(bodyParser.json());
nodemon
- 소스를 변경을 감지하여 자동으로 서버를 재시작 해주는 tool
npm install nodemon --save-dev
* --save-dev: devDependencies로 개발 단계에서만 사용하도록 설정
-> package.json에 nodemon으로 시작하는 script 추가
'개발 > JavaScript' 카테고리의 다른 글
| [Node.js] login route (0) | 2022.07.22 |
|---|---|
| [Node.js] 정보보호, Bcrypt (0) | 2022.07.21 |
| [바닐라 JS] PaintJS - Fill, Save (0) | 2022.04.04 |
| [바닐라 JS] PaintJS - color, brush (0) | 2022.04.03 |
| [바닐라 JS] PaintJS - canvas (0) | 2022.04.03 |