Commit 7a918c31 authored by 박상호's avatar 박상호 🎼
Browse files

1-6

parents 9c17ddca 3ba7cf83
import express from 'express' import express from 'express';
// import bodyParser from "body-parser";
import connectDb from './schemas/index.js' import connectDb from './schemas/index.js'
import userRouter from "./routes/user.routes.js"; import userRouter from "./routes/user.routes.js";
import productRouter from './routes/product.routes.js';
import path from 'path'
import kakaopayRoutes from './routes/kakaopay.routes.js'
import config from './config.js'
import cors from 'cors'
connectDb() connectDb()
// const createError = require('http-errors');
// const express = require('express');
// const path = require('path');
// const cookieParser = require('cookie-parser');
// const logger = require('morgan');
// const port = 3030;
// const indexRouter = require('./routes/index');
const app = express(); const app = express();
// connect();
// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'pug');
// app.use(logger('dev'));
app.use(express.json()); app.use(express.json());
// app.use(express.urlencoded({ extended: false })); app.use(cors())
// app.use(cookieParser(process.env.JWT_SECRET));
// app.use(express.static(path.join(__dirname, 'public')));
// app.use('/', indexRouter); app.use(express.static(path.join(process.cwd(), 'dist')))
// app.use(bodyParser.urlencoded({ extended: true }))
// app.listen(port, () => console.log(port)); // app.use('/', indexRouter);
app.listen(3001, () => console.log('Listenning')); app.use('/', kakaopayRoutes)
app.use('/api/users',userRouter)
app.use(userRouter) app.use('/api/products', productRouter)
// 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 app.listen(config.port, () => {
// res.status(err.status || 500); console.info('Server started on port %s.', config.port)
// res.render('error'); })
// });
// module.exports = app;
\ No newline at end of file
...@@ -2,7 +2,16 @@ const config = { ...@@ -2,7 +2,16 @@ const config = {
env: process.env.NODEENV || 'development', env: process.env.NODEENV || 'development',
port: process.env.PORT || 3001, port: process.env.PORT || 3001,
jwtSecret: process.env.JWT_SECRET || 'My_Secret_Key', jwtSecret: process.env.JWT_SECRET || 'My_Secret_Key',
mongoDbUri: process.env.MONGEDB_URI || 'mongodb://localhost/' mongoDbUri: process.env.MONGEDB_URI || 'mongodb://localhost/shopping-mall',
kakaoAdminKey: 'b2dda7685c5b2990684d813e362cff07'
} }
export default config // const config = {
\ No newline at end of file // port: 3001,
// kakaoAdminKey: 'b2dda7685c5b2990684d813e362cff07',
// }
export default config
// export default config
\ No newline at end of file
// import { RequestHandler } from "express";
import fetch from 'node-fetch'
import config from "../config.js";
const success = (req, res) => {
console.log('kakaopay success route')
console.log('req body:', req.body)
return res.json({
message: 'Success'
})
}
const fail = (req, res) => {
console.log('kakaopay fail route')
console.log('req body:', req.body)
return res.json({
message: 'Failed'
})
}
const cancel = (req, res) => {
console.log('kakaopay cancel route')
console.log('req body:', req.body)
return res.json({
message: 'Canceled'
})
}
const singleTest = async (req, res) => {
console.log("asdaf")
console.log(req.body)
const item = req.body
// set data
const data = []
for (let property in item) {
let encodedKey = encodeURIComponent(property);
let encodedValue = encodeURIComponent(item[property]);
data.push(encodedKey + "=" + encodedValue);
}
const bodyData = data.join('&') // encode data (application/x-www-form-urlencoded)
const response = await fetch('https://kapi.kakao.com/v1/payment/ready', {
method: 'POST',
headers: {
'Authorization': `KakaoAK ${config.kakaoAdminKey}`,
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
},
body: bodyData,
})
// console.log(response)
const resp = await response.json()
console.log(resp)
res.json({redirect_url: resp.next_redirect_pc_url})
}
export default {
success,
fail,
cancel,
singleTest,
}
import Product from "../schemas/Product.js";
const regist = async (req, res) => {
console.log('req.body=', req.body)
const { pro_name, price, stock, main_category, sub_category, description, main_image, detail_image } = req.body.product
try {
const newProduct = await new Product ({
pro_name, price, stock, main_category, sub_category, description, main_image, detail_image
}).save()
console.log(newProduct)
res.json(newProduct)
} catch (error) {
console.log(error)
res.status(500).send('죄송합니다. 다시 입력해 주십시오.')
}
}
export default { regist }
\ No newline at end of file
import User from "../models/User.js"; import User from "../models/User.js";
import isLength from 'validator/lib/isLength.js'
const signup = async (req, res) => { const signup = async (req, res) => {
const { name, email, password } = req.body console.log(req.body)
console.log('req.body.name=', req.body.name)
const { name, number1, number2, id, password, password2, tel } = req.body
try { try {
if(!isLength(password,{min:8, max:15})){
return res.status(422).json({message: '비밀번호는 8-15자리로 입력해주세요.'})
}
const newUser = await new User ({ const newUser = await new User ({
name, name,
email, number1,
password number2,
id,
password,
password2,
tel
}).save() }).save()
console.log(newUser) console.log(newUser)
res.json(newUser) res.json(newUser)
} catch (error) { } catch (error) {
console.log(error) console.log(error)
res.status(500).send('죄송합니다. 다시 입력해 주십시오.') res.status(500).json({message:'죄송합니다. 다시 입력해 주십시오.'})
} }
} }
......
...@@ -5,9 +5,9 @@ const { String } = mongoose.Schema.Types ...@@ -5,9 +5,9 @@ const { String } = mongoose.Schema.Types
const UserSchema = new mongoose.Schema({ const UserSchema = new mongoose.Schema({
name: { name: {
type: String, type: String,
required: true, required: true, // 꼭 필요한 값
}, },
email: { id: {
type: String, type: String,
required: true, required: true,
unique: true, unique: true,
...@@ -15,7 +15,21 @@ const UserSchema = new mongoose.Schema({ ...@@ -15,7 +15,21 @@ const UserSchema = new mongoose.Schema({
password: { password: {
type: String, type: String,
required: true, required: true,
select: true, },
number1:{
type:String,
required:true,
unique:true
},
number2:{
type:String,
required:true,
unique:true
},
tel:{
type:String,
required:true,
unique:true
}, },
role: { role: {
type: String, type: String,
......
...@@ -5,15 +5,19 @@ ...@@ -5,15 +5,19 @@
"type": "module", "type": "module",
"main": "app.js", "main": "app.js",
"scripts": { "scripts": {
"dev": "nodemon app.js",
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },
"keywords": [], "keywords": [],
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"cors": "^2.8.5",
"express": "^4.17.1", "express": "^4.17.1",
"mongoose": "^5.11.9", "mongoose": "^5.11.9",
"node-fetch": "^2.6.1",
"nodemon": "^2.0.6", "nodemon": "^2.0.6",
"validator": "^13.5.2" "validator": "^13.5.2",
"multer": "^1.4.2"
} }
} }
import express from 'express'
import kakaopayCtrl from '../controllers/kakaopay.controller.js'
const router = express.Router()
router.route('/kakaopay/success')
.get(kakaopayCtrl.success)
router.route('/api/kakaopay/fail')
.get(kakaopayCtrl.fail)
router.route('/api/kakaopay/cancel')
.get(kakaopayCtrl.cancel)
router.route('/api/kakaopay/test/single')
.post(kakaopayCtrl.singleTest)
export default router
import express from "express";
import productCtrl from '../controllers/product.controller.js';
const router = express.Router()
router.route('/regist')
.post(productCtrl.regist)
export default router
\ No newline at end of file
...@@ -3,7 +3,7 @@ import userCtrl from '../controllers/user.controller.js'; ...@@ -3,7 +3,7 @@ import userCtrl from '../controllers/user.controller.js';
const router = express.Router() const router = express.Router()
router.route('/api/users/signup') router.route('/signup')
.post(userCtrl.signup) .post(userCtrl.signup)
.get(userCtrl.hello) .get(userCtrl.hello)
......
import mongoose from 'mongoose'
const { String, Number, Array } = mongoose.Schema.Types
const ProductSchema = new mongoose.Schema({
pro_name: {
type: String,
required: true,
},
price: {
type: String,
required: true,
},
stock: {
type: String,
required: true
},
purchase: {
type: String,
required: true,
default: 0
},
main_category: {
type: String,
required: true,
},
sub_category: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
main_image: {
type: String,
required: true,
},
detail_image: {
type: String,
required: true,
}
}, {
timestamps: true
})
export default mongoose.models.Product || mongoose.model('Product', ProductSchema)
\ No newline at end of file
import mongoose from 'mongoose'
const { String } = mongoose.Schema.Types
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
id: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
select: false
},
confirm_password:{
type: String,
required: true,
select: false
},
phoneNumber: {
type: String,
required: true,
},
role: {
type: String,
required: true,
default: 'user',
enum: ['user', 'admin', 'root']
},
birth: {
type: String,
required: true,
},
sex: {
type: String,
required: true,
}
}, {
timestamps: true
})
export default mongoose.models.User || mongoose.model('User', UserSchema)
\ No newline at end of file
...@@ -4,9 +4,9 @@ import config from '../config.js'; ...@@ -4,9 +4,9 @@ import config from '../config.js';
const connection = {} const connection = {}
async function connectDb() { async function connectDb() {
// if (connection.isConnection) { if (connection.isConnection) {
// return return
// } }
const db = await mongoose.connect(config.mongoDbUri, { const db = await mongoose.connect(config.mongoDbUri, {
useNewUrlParser: true, useNewUrlParser: true,
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment