-
카테고리
-
세부 분야
풀스택
-
해결 여부
미해결
배너가 불러와지지 않습니다
22.12.11 20:09 작성 22.12.11 20:10 수정 조회수 174
0
const express = require("express");
const cors = require("cors");
const app = express();
const models = require("./models");
const multer = require("multer");
// const upload = multer({ dest: "uploads/" });
const upload = multer({
storage: multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads/");
},
filename: function (req, file, cb) {
cb(null, file.originalname);
},
}),
});
const port = 8080;
app.use(express.json());
app.use(cors());
app.use("/uploads", express.static("uploads"));
app.get("/banners", (req, res) => {
models.Banner.findAll({
limit: 2,
})
.then((result) => {
res.send({
banners: result,
});
})
.catch((error) => {
console.error(error);
res.status(500).send("에러가 발생했습니다");
});
});
app.get("/products", (req, res) => {
// const query = req.query;
// console.log("QUERY : ", query);
models.Product.findAll({
// limit: 1,
// where : { }
order: [["createdAt", "DESC"]],
attributes: ["id", "name", "price", "seller", "createdAt", "imageUrl"],
})
.then((result) => {
console.log("PRODUCT : ", result);
res.send({
products: result,
});
})
.catch((error) => {
console.error(error);
res.status(400).send("에러 발생");
});
// res.send({
// products: [
// {
// id: 1,
// name: "농구공",
// price: 100000,
// seller: "조던",
// imageUrl: "images/products/basketball1.jpeg",
// },
// {
// id: 2,
// name: "축구공",
// price: 50000,
// seller: "메시",
// imageUrl: "images/products/soccerball1.jpg",
// },
// {
// id: 3,
// name: "키보드",
// price: 10000,
// seller: "그랩",
// imageUrl: "images/products/keyboard1.jpg",
// },
// ],
// });
});
app.post("/products", (req, res) => {
const body = req.body;
const { name, price, seller, description, imageUrl } = body;
if (!name || !price || !seller || !description || !imageUrl) {
res.status(400).send("모든 필드를 입력해주세요.");
}
models.Product.create({
name, // name = name
price,
seller,
description,
imageUrl,
})
.then((result) => {
console.log("상품 생성 결과 : ", result);
res.send({
result, // result : result
});
})
.catch((err) => {
console.error(err);
res.status(400).send("상품 업로드에 문제가 발생했습니다.");
});
res.send({
body, //body : body
});
});
app.get("/products/:id", (req, res) => {
const params = req.params;
const { id } = params;
// res.send(`id는 ${id} 입니다.`);
models.Product.findOne({
where: {
id: id,
},
})
.then((result) => {
console.log("PRODUCT : ", result);
res.send({
product: result,
});
})
.catch((error) => {
console.error(error);
res.status(400).send("상품 조회에 에러가 발생했습니다.");
});
});
// 이미지 한개만 요청하는 경우
app.post("/image", upload.single("image"), (req, res) => {
const file = req.file;
console.log(file);
res.send({ imageUrl: file.path });
});
app.listen(port, () => {
console.log("그랩의 쇼핑몰 서버가 돌아가고 있습니다.");
models.sequelize
.sync()
.then(() => {
console.log("DB 연결 성공!");
})
.catch((err) => {
console.error("DB 연결 에러 ㅠ");
process.exit();
});
});
import React from "react";
import "./index.css";
import axios from "axios";
import { Link } from "react-router-dom";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import { API_URL } from "../config/constants.js";
import { Carousel } from "antd";
dayjs.extend(relativeTime); // 기능 확장
function MainPage() {
const [products, setProducts] = React.useState([]);
const [banners, setBanners] = React.useState([]);
React.useEffect(function () {
axios
.get(
//"https://daa98a8e-bcac-42e0-a0ae-c5562a66248a.mock.pstmn.io/products"
// "http://localhost:8080/products"
`${API_URL}/products`
)
.then(function (result) {
const products = result.data.products;
setProducts(products);
})
.catch(function (error) {
console.error("에러 발생 : ", error);
});
axios
.get(`${API_URL}/banners`)
.then((result) => {
const banners = result.data.banners;
setBanners(banners);
})
.catch((error) => {
console.error("에러 발생 : ", error);
});
}, []);
return (
<div>
<Carousel autoplay autoplaySpeed={3000}>
{banners.map((banner, index) => {
return (
<Link to={banner.href}>
<div id="banner">
<img src={`${API_URL}/${banner.imageUrl}`} />
</div>
</Link>
);
})}
</Carousel>
<h1 id="product-headline">판매되는 상품들</h1>
<div id="product-list">
{products.map(function (product, index) {
return (
<div className="product-card">
<Link className="product-link" to={`/products/${product.id}`}>
<div>
<img
className="product-img"
src={`${API_URL}/${product.imageUrl}`}
/>
</div>
<div className="product-contents">
<span className="product-name">{product.name}</span>
<span className="product-price">{product.price}원</span>
<div className="product-footer">
<div className="product-seller">
<img
className="product-avatar"
src="images/icons/avatar.png"
/>
<span>{product.seller}</span>
</div>
<span className="product-date">
{dayjs(product.createdAt).fromNow()}
</span>
</div>
</div>
</Link>
</div>
);
})}
</div>
</div>
);
}
export default MainPage;
Server server.js
React index.js
콘솔창 에러
banners DB
products DB
차례대로 첨부해드렸습니다.
도저히 안되어서 선생님 코드를 복붙까지 했는데 안되네요ㅠㅠ 도와주세요..
답변을 작성해보세요.
0
답변 1