728x90
Express JS, Quasar, MongoDB 구조
사용 툴 : VSCode, GitHub(형상관리, 프로젝트 개발 들어갈 때 GitLab으로 변경할 예정)
DB : MongoDB(Docker)
project 폴더 생성
mkdir <project-name>
quasar 프로젝트 생성
quasar create <quasar-project-name>
cd <quasar-project-name>
npm install vue-router@4
npm install vuex@next
quasar new boot axios
/boot/axios.js로 이동 후 수정
import { boot } from 'quasar/wrappers'
import axios from 'axios'
// Be careful when using SSR for cross-request state pollution
// due to creating a Singleton instance here;
// If any client changes this (global) instance, it might be a
// good idea to move this instance creation inside of the
// "export default () => {}" function below (which runs individually
// for each client)
const api = axios.create({ baseURL: 'https://api.example.com' })
export default boot(({ app }) => {
// for use inside Vue files (Options API) through this.$axios and this.$api
app.config.globalProperties.$axios = axios
// ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
// so you won't necessarily have to import axios in each vue file
app.config.globalProperties.$api = api
// ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
// so you can easily perform requests against your app's API
})
export { api }
express 프로젝트 생성
express 전역 설치 후
npm install express-generator -g
express <express-project-name>
cd <express-project-name>
npm install
quasar
quasar.conf.js 이동
build: {
vueRouterMode: 'hash', // available values: 'hash', 'history'
// transpile: false,
// publicPath: '/',
// Add dependencies for transpiling with Babel (Array of string/regex)
// (from node_modules, which are by default not transpiled).
// Applies only if "transpile" is set to true.
// transpileDependencies: [],
// rtl: true, // https://quasar.dev/options/rtl-support
// preloadChunks: true,
// showProgress: false,
// gzip: true,
// analyze: true,
// Options below are automatically set depending on the env, set them if you want to override
// extractCSS: false,
// https://quasar.dev/quasar-cli/handling-webpack
// "chain" is a webpack-chain object https://github.com/neutrinojs/webpack-chain
chainWebpack (/* chain */) {
//
},
distDir:'../backend/public/',
htmlFilename:'index.html'
},
build 부분에 distDir, htmlFilename 설정.
proxy 설정
devServer: {
server: {
type: 'http'
},
port: 8080,
open: true, // opens browser window automatically
proxy:{
'/api':'http://localhost:3000',
changeOrigin: true,
pathRewrite:{
'^/api':''
}
}
},
express의 기본 포트 3000을 사용해서 타켓 url이 3000포트
express
nodemon 설치
npm install nodemon --save-dev
mongoose 설치
npm install mongoose
express 프로젝트 루트디렉토리에 db.js 파일 생성 후 DB Connection 설정
//DB Connection
const mongoose = require('mongoose');
module.exports = () => {
function connect() {
mongoose.connect('mongodb://<ID>:<Password>@localhost:27017/<DB명>',function(err) { // .connect is db connection
if(err) {
console.log('mongodb connection error : ', err);
}
console.log('mongodb connected');
})
}
connect();
mongoose.connection.on('disconnected',connect);
}
app.js 수정
//생략
var db = require('./db);
var app = express();
db();
//생략
db연결은 express 아래 쪽에다가 해줘야함. express 먼저 연결 후 db 연결이 이뤄져야함.
models 폴더 생성
board.js 파일 생성
const mongoose = require('mongoose');
const boardSchema = new mongoose.Schema({
title : String,
writer : String,
});
//Create Board
boardSchema.statics.create = function (payload) {
const board = new this(payload);
return board.save();
};
//Find All
boardSchema.statics.findAll = function () {
return this.find({});
}
module.exports = mongoose.model('Board',boardSchema);
routes 폴더로 이동
board.js 파일 생성
const router = require('express').Router();
const Board = require('../models/board');
router.get('/',(req,res)=>{
Board.find()
.then(()=>{
// if(!boards.length) return res.status(404).send({err:'Board Not Found'});
// res.send(`find successfully: ${boards}`);
})
.catch(err => res.status(500).send(err));
res.send('success!');
})
module.exports = router;
app.js 파일 수정
//생략
var boardRouter = require('./routes/board');
//생략
app.use('/board',boardRouter);
//생략
app.js 최종
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var db = require('./db');
var indexRouter = require('./routes/index');
var boardRouter = require('./routes/board');
var app = express();
db();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/board',boardRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
728x90
'おもちゃプロジェクト' 카테고리의 다른 글
개인 블로그 만들기(4) (0) | 2022.03.30 |
---|---|
개인 블로그 만들기(3) (0) | 2022.03.17 |
개인 블로그 만들기 (0) | 2022.03.07 |
토이프로젝트(4)- 주변 맛집 (2) | 2021.11.24 |
토이프로젝트(3)- 주변 맛집 (0) | 2021.11.22 |
Comment