오류때문에 난리나서 머리 터질것같다. Create를 insomnia를 통해서 넣는걸로 배워서 클라이언트가 직접입력한 값들을 어떻게 DB에 전달하고 저장할지 한참 찾다가 미니 프로젝트와 비슷한 ajax방식으로 시도해봤더니 성공.
function posting(){
let title1 = $('#title').val()
let subtitle1 = $('#subtitle').val() //미니 프로젝트때랑 비슷하게
let category1 = $('#category').val() // 사용자 입력값을 끌어와서
let context1 = $('#context').val()
$.ajax({
type: "POST",
url: 'api/posts',
data:{
title: title1, //jQurey 식으로 데이터를 쏴주고
subtitle: subtitle1,
category: category1,
context: context1
},
success: function(response) { //서버쪽에서 success가 오면 리스트로 리다이렉트
if (response["result"] == "success") {
alert("저장완료");
window.location.href= " /list "
}
}
})
}
router.post("/posts", async(req,res) => { // /post url로 데이터가 오고
const { title, subtitle, context, category } = req.body; //리퀘스트 바디에 데이터를
await Posts.create({ title, subtitle, context, category }); //DB에 create
res.send ({ result : "success" }); //결과 전송
});
node.js에서는 데이터가 저장될때 "Schema" 라는 와플 틀과 비슷한 데이터를 저장하는 방식을 적어놓는게 필요하다하여 게시판 Schema도 저장해두었다.
const mongoose = require("mongoose");
const { Schema } = mongoose;
const postsSchema = new Schema({
title: {
type: String,
required: true,
},
subtitle: {
type: String,
required: true
},
context: {
type: String,
required: true
},
category: {
type: String,
required: true
},
date: {
type: String,
required: true,
},
});
module.exports = mongoose.model("Posts",postsSchema)