2022-03-21(TIL)

황인호·2022년 6월 7일
0

TIL 모음

목록 보기
10/119

오늘해야할일들

  • 오전 07시30분 기상 → [미흡...밍기적대다가 8시에 일어남...]
  • 알고리즘 1문제 풀기 → [풀이작성까지 완료]
  • 오전09시 CODE CS스터디 모임 참석할것! → [완료]
  • 오전 09시 30분부터 집중해서 강의듣고 개인 과제할것!

금일 배운내용 아래 작성 필요

코드를 작성하며 해당 코드는 각각 무엇을 의미하는지 꼼꼼하게 기재할것!

오늘은 열심히 개인과제를 하기위해서 노력을해보았다!!

const connect = require("./schemas/index");

connect(); // mongoose의 connect함수를 실행하는용도의 코드

app.use(express.json()); // 어떤 미들웨어냐 body로 들어오는 코드를 사용할수있게 도와주는
미들웨어이다.
json 형태의 데이터를 파싱(내가원하는 대로 가공하여 서버에서 원하는때 불러올수있도록하는것)!
해준다!!

app.use("api",[blogRouter]); //localhost:3000 뒤에다가 /api를 붙여야 blog를 실행
하겠다는 뜻이다.

아래의 코드는 mongoose를 실행하려고하는 코드이다.

const mongoose = require("mongoose");


const connect = () => {
    mongoose.connect("mongodb://localhost:27017/blog", {ignoreUndefined: true} ).catch((err)=> {
        console.error(err);
    });
};

module.exports = connect;
const express = require('express') //require는 불러온다는 뜻이다.
const Blog = require("../schemas/blog") // schemas에 있는blog파일을 가져오겠다는뜻이다.

router.get('/', (req, res) => { // '/' -> '/api/'라는 뜻이다.
	res.send('this is home page');
});

router.get('blog', async(req, res) => { // '/blog는  '/api/blog' 라는 뜻이다.
	const blog = await Blog.find(); // schema에 저장된 내용을 가져오겠다는 뜻이다.
	res.json({
			blog
		});
});

router.post("/blog", async(req, res) => { // 블로그 생성 api
	const {blogId, title, category, content} = req,body; // 원하는 데이터를
한번에 변수로 만드는 작업으로 비구조화라고한다.

	const blog = await Blog.find({ blogId }); // 데이터 베이스에서 동일한
블로그아이디가 있는지 찾는다
	if (blog.length) {
			return res.status(400).json({ sucess: false, errorMessage : "이미 있는 데이터입니다."});
	}

	const createBlog = await Blog.create({ blogId, title, category, content});
	res.json({ blogId : createdBlog }); // 변수에 넣어서 응답값으로 내보낸다.
});

module.exports = router; // 위에 정리한 내용을 모듈로써 내보내겠다는 약속

프론트엔드 연결하는 방법도 찾았다!!~

const express = require("express");
const app = express();

const server = app.listen(3000, () => {
	console.log('3000포트로 켜졌습니다.')
});

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);

app.get('/', function (req, res) {
	res.render('index.html')
});

app.get('/about', function(reqw, res) {
	res.render('about.html')
});
profile
성장중인 백엔드 개발자!!

0개의 댓글