CRUD : Create(생성), Read(읽기), Update(갱신), Delete(삭제) 를 묶어서 일컫는 말이다.
생성한 폴더 아래 추가적으로 app폴더 그 안에 config, controllers, models, routes 폴더까지만 생성
express, sequelize, pg, pg-hstore, body-parser
npm install express sequelize pg pg-hstore body-parser cors --save
설치 완료
현재 package.json 모습
server.js 생성
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
var corOptions = {
origin: "http://localhost:8081",
};
app.use(cors(corOptions));
// parse requests of content-type - application/json
app.use(bodyParser.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to my application." });
});
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on Port ${PORT}!`);
});
module.exports = {
HOST: "localhost",
USER: "postgres",
// password에는 설치할때 설정한 비밀번호 입력!
PASSWORD: "1234"
DB: "my_DB",
dialect: "postgres"
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
app/models 폴더에 index.js 생성
const dbConfig = require('../config/db.config.js');
const Sequelize = require('sequelize');
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
});
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.tutorials = require("./tutorial.model.js")(sequelize, Sequelize);
module.exports = db;
models 폴더에 tutorial.model.js 생성
module.exports = (sequelize, Sequelize) => {
const Tutorial = sequelize.define("tutorial", {
title: {
type: Sequelize.STRING
},
description: {
type: Sequelize.STRING
},
published: {
type: Sequelize.BOOLEAN
}
});
return Tutorial
};
"tutorial"
테이블을 나타낸다.Express : Nodejs 서버 프레임워크
Sequelize : 쉽게 서버와 연결해주는 nodejs(javascript) 라이브러리
pg : PostgreSQL을 사용하기 위한 모듈
pg-hstore : 데이터를 PostgreSQL hstore
type 으로 변환해주는 모듈
body-parser : 요청 구문분석 and req.body 생성에 필요
cors : Express 미들웨어에서 CORS 사용을 위해 설치
CORS
는 Cross Origin Resource Sharing의 약자로 도메인 및 포트가 다른 서버로 클라이언트가 요청했을 때 브라우저가 보안상의 이유로 API를 차단하는 문제입니다. 예로 들면 로컬에서 클라이언트는 3000 포트로 서버는 10000 포트로 서버를 띄웠을때 또는 로컬 서버에서 다른 서버로 호출할 때 발생하게 됩니다.
출처 : https://firework-ham.tistory.com/70
References
https://bezkoder.com/node-express-sequelize-postgresql/