如何使用nodejs reactjs提供图像

bz4sfanl  于 2023-10-17  发布在  Node.js
关注(0)|答案(1)|浏览(108)

我想在前端显示图像。图像以静态路径保存在PostgreSQL数据库中。我试图设置一个Express服务器来提供这些图像,但它不工作。
代码:

产品卡

import React, { useEffect, useState } from "react";
import axios from "../config/axios";
import ProductItem from "./ProductItem";

function ProductCard() {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    const getData = async () => {
      try {
        const response = await axios.get("/api/product");
        setProducts(response.data);
      } catch (error) {
        console.error("Error fetching product data:", error);
      }
    };

    getData();
  }, []);

  return (
    <>
      {products?.map((el) => {
        return (
          <ProductItem
            key={el?.id}
            src={el?.img}
            name={el?.name}
            description={el?.description}
            price={el?.price}
            file={el?.file}
          />
        );
      })}
    </>
  );
}

export default ProductCard;

productItem

import React from "react";
import { Card } from "antd";
const { Meta } = Card;

function ProductItem({ name, description, price, file }) {
  console.log(file);
  return (
    <>
      <Card
        hoverable
        style={{ width: 240 }}
        cover={<img alt="example" src={file} />}
      >
        <Meta title={name} description={description} />
        <p className="mt-2 flex justify-end">{price}</p>
      </Card>
    </>
  );
}

export default ProductItem;
  • 这是我在日志文件中得到的:*
1696953634614-281617729calendar1.jpg
1696953636442-290084764calendar1.jpg
1696953636442-290084764calendar1.jpg

服务器

const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const bodyParse = require("body-parser");

const authRoute = require("./routes/authRoute");
const productRoute = require("./routes/productRoute");
const userRoute = require("./routes/userRoute");
const path = require("path");
const app = express();

app.use(cors());
app.use(morgan("dev"));
app.use(bodyParse.json({ limit: "10mb" }));
app.use("/assets", express.static("/assets"));
app.use(express.json());

app.use("/", authRoute);
app.use("/api", productRoute);
app.use("/users", userRoute);

app.use("/assets", express.static(path.join(__dirname, "assets")));

const port = process.env.PORT || 8000;

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

怎么样?谢谢你

gorkyyrv

gorkyyrv1#

由于您从“/assets”路径提供文件,因此需要在ProductItem组件中使用正确的路径

<img alt="example" src={`/assets/${file}`} />

相关问题