반응형
위 글에서 하단에 있는 express-generator 사용하지 않고 node 세팅을 먼저 하고 오자
mySQL도 설치 및 계정 생성이 되어 있어야 한다
구조는 위와 같다
① mySQL 설정 및 연동
⑴ backend/config/config.js
module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "12341234",
DB: "shabping"
};
mySQL에서 사용할 정보를 정해서 설정한다
⑵ backend/model/db.js
const mysql = require("mysql");
const dbConfig = require("../config/config.js");
// Create a connection to the database
const connection = mysql.createConnection({
host: dbConfig.HOST,
user: dbConfig.USER,
password: dbConfig.PASSWORD,
database: dbConfig.DB
});
// open the MySQL connection
connection.connect(error => {
if (error) throw error;
console.log("Successfully connected to the database.");
});
module.exports = connection;
② 모델 설정
⑴ backend/model/customer.js
const sql = require("./db.js");
// constructor
const Customer = function(customer) {
this.email = customer.email;
this.name = customer.name;
this.active = customer.active;
};
Customer.create = (newCustomer, result) => {
sql.query("INSERT INTO customers SET ?", newCustomer, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("created customer: ", { id: res.insertId, ...newCustomer });
result(null, { id: res.insertId, ...newCustomer });
});
};
Customer.findById = (customerId, result) => {
sql.query(`SELECT * FROM customers WHERE id = ${customerId}`, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
if (res.length) {
console.log("found customer: ", res[0]);
result(null, res[0]);
return;
}
// not found Customer with the id
result({ kind: "not_found" }, null);
});
};
Customer.getAll = result => {
sql.query("SELECT * FROM customers", (err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
console.log("customers: ", res);
result(null, res);
});
};
Customer.updateById = (id, customer, result) => {
sql.query(
"UPDATE customers SET email = ?, name = ?, active = ? WHERE id = ?",
[customer.email, customer.name, customer.active, id],
(err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
if (res.affectedRows == 0) {
// not found Customer with the id
result({ kind: "not_found" }, null);
return;
}
console.log("updated customer: ", { id: id, ...customer });
result(null, { id: id, ...customer });
}
);
};
Customer.remove = (id, result) => {
sql.query("DELETE FROM customers WHERE id = ?", id, (err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
if (res.affectedRows == 0) {
// not found Customer with the id
result({ kind: "not_found" }, null);
return;
}
console.log("deleted customer with id: ", id);
result(null, res);
});
};
Customer.removeAll = result => {
sql.query("DELETE FROM customers", (err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
console.log(`deleted ${res.affectedRows} customers`);
result(null, res);
});
};
module.exports = Customer;
③ 라우트 설정
⑴ backend/routes/customer.js
module.exports = app => {
const customers = require("../controller/customer.js");
// Create a new Customer
app.post("/customers", customers.create);
// Retrieve all Customers
app.get("/customers", customers.findAll);
// Retrieve a single Customer with customerId
app.get("/customers/:customerId", customers.findOne);
// Update a Customer with customerId
app.put("/customers/:customerId", customers.update);
// Delete a Customer with customerId
app.delete("/customers/:customerId", customers.delete);
// Create a new Customer
app.delete("/customers", customers.deleteAll);
};
④ server.js 수정
require("./app/routes/customer.routes.js")(app); // 추가
// app.listen() 위에 윗줄 추가👆🏻
// set port, listen for requests
app.listen(5000, () => {
console.log("Server is running on port 5000.");
});
⑤ controller 생성
⑴ backend/controller/customer.js
const Customer = require("../model/customer.js");
// Create and Save a new Customer
exports.create = (req, res) => {
// Validate request
if (!req.body) {
res.status(400).send({
message: "Content can not be empty!"
});
}
// Create a Customer
const customer = new Customer({
email: req.body.email,
name: req.body.name,
active: req.body.active
});
// Save Customer in the database
Customer.create(customer, (err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while creating the Customer."
});
else res.send(data);
});
};
// Retrieve all Customers from the database.
exports.findAll = (req, res) => {
Customer.getAll((err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while retrieving customers."
});
else res.send(data);
});
};
// Find a single Customer with a customerId
exports.findOne = (req, res) => {
};
// Update a Customer identified by the customerId in the request
exports.findOne = (req, res) => {
Customer.findById(req.params.customerId, (err, data) => {
if (err) {
if (err.kind === "not_found") {
res.status(404).send({
message: `Not found Customer with id ${req.params.customerId}.`
});
} else {
res.status(500).send({
message: "Error retrieving Customer with id " + req.params.customerId
});
}
} else res.send(data);
});
};
exports.update = (req, res) => {
// Validate Request
if (!req.body) {
res.status(400).send({
message: "Content can not be empty!"
});
}
Customer.updateById(
req.params.customerId,
new Customer(req.body),
(err, data) => {
if (err) {
if (err.kind === "not_found") {
res.status(404).send({
message: `Not found Customer with id ${req.params.customerId}.`
});
} else {
res.status(500).send({
message: "Error updating Customer with id " + req.params.customerId
});
}
} else res.send(data);
}
);
};
// Delete a Customer with the specified customerId in the request
exports.delete = (req, res) => {
Customer.remove(req.params.customerId, (err, data) => {
if (err) {
if (err.kind === "not_found") {
res.status(404).send({
message: `Not found Customer with id ${req.params.customerId}.`
});
} else {
res.status(500).send({
message: "Could not delete Customer with id " + req.params.customerId
});
}
} else res.send({ message: `Customer was deleted successfully!` });
});
};
// Delete all Customers from the database.
exports.deleteAll = (req, res) => {
Customer.removeAll((err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while removing all customers."
});
else res.send({ message: `All Customers were deleted successfully!` });
});
};
⑥ node 서버 실행
node server.js
위 메시지가 뜨면서 서버가 잘 실행되는 것을 볼 수 있다
⑦ Postman에서 POST로 데이터 넣기
넣을 데이터를 입력하고 Send 버튼을 클릭하면
아래처럼 데이터가 잘 들어가는 것을 확인할 수 있다
⑧ node 서버에서 rest API 확인
json 형식으로 데이터를 잘 가져오는 것을 확인할 수 있다
아래 사이트에 있는 글을 참고했다
bezkoder.com/node-js-rest-api-express-mysql/
반응형