최근 Toast Picker Toyproject를 하며 NoSQL인 mongoDB 활용을 해본 이후로 MySQL도 활용해보고 싶어서 시작하게 되었다.
MySQL설정하기
https://velog.io/@lsc90726/MySQL
백엔드 작업부터 시작하였다.
최초 설정과 MySQL연결에 중점을 두었다.
cd backend
npm init -y
npm i express mysql nodemon
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"start": "nodemon index.js"
//nodemon 설정해주기
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.1",
"mysql": "^2.18.1",
"nodemon": "^2.0.20"
}
}
import express from "express";
const app = express();
app.listen(8800, () => {
console.log("Connected to Backend!");
});
C:\Users\승찬이\Desktop\book\backend>node index.js
Connected to Backend!
C:\Users\승찬이\Desktop\book\backend>npm start
> backend@1.0.0 start
> nodemon index.js
[nodemon] 2.0.20
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
Connected to Backend!
MySQL 연결하기
import express from "express";
import mysql from "mysql";
const app = express();
//mysql db와 연결하기
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "****",
database: "data",
});
app.get("/", (req, res) => {
res.json("hello this is the backend");
});
app.listen(8800, () => {
console.log("Connected to Backend!");
});
정상적으로 연결완료 아직 DB가 없어서 [ ]
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '****';
Query OK, 0 rows affected, 1 warning (0.00 sec)
POST 하기
//데이터 입력하기
app.post("/books", (req, res) => {
const q = "INSERT INTO books (`title`,`desc`,`cover`) VALUES (?)";
//테스트용
const values = [
"title from backend",
"desc from backend",
"cover pic from backend",
];
//데이터 입력용
const values = [req.body.title, req.body.desc, req.body.cover];
db.query(q, [values], (err, data) => {
if (err) return res.json(err);
return res.json("책 만들기 성공");
});
});
Postman 에서 test하기
GET 하기
//전체 데이터 가져오기
app.get("/books", (req, res) => {
const q = "SELECT * FROM books";
db.query(q, (err, data) => {
if (err) return res.json(err);
return res.json(data);
});
});