유데미 Node.js 강의를 보면
기존의 쇼핑 사이트는 데이터를 json형태로 관리 하였습니다.
이제는 Mysql을 통해서 데이터를 집어 넣도록 하겠습니다.
제품을 관리하는
models폴더 안에 있는 product.js에서
제품을 저장 할 수 있게하는 save() 기능을 만들도록 하겠습니다.
module.exports = class Product {
constructor(id, title, imageUrl, description, price) {
this.id = id;
this.title = title;
this.imageUrl = imageUrl;
this.description = description;
this.price = price;
}
save() {
return db.execute
('INSERT INTO products (title,price,description,imageUrl) value (?,?,?,?)',
[this.title,this.price,this.description,this.imageUrl]
);
}
이렇게 데이터를 controller로 보내면 됩니다.
exports.postAddProduct = (req, res, next) => {
const title = req.body.title;
const imageUrl = req.body.imageUrl;
const price = req.body.price;
const description = req.body.description;
const product = new Product(null, title, imageUrl, description, price);
product
.save()
.then(() =>{
res.redirect('/');
})
.catch(err=>{
console.log(err);
});
};
product.save()부분에 promise를 사용합니다. 이떄 then 이후로는 코드가 작동하면 실행이고, cathch부분은 에러가 나왔을 경우 에러의 log를 보기 위해서 입니다.
이렇게 입력을 하고 Add Product를 누르면
sql에 데이터가 추가가 되기도 하고 추가된 데이터가 불러와 집니다.
'Node.js' 카테고리의 다른 글
Node.js 쿼리 인젝션 방지 (0) | 2023.02.25 |
---|---|
Node.js와 Mysql 연동 (0) | 2023.02.25 |
node.js 설정 하기 (0) | 2023.02.11 |