图像未显示在Heroku上

问题描述

我正在构建一个MERN应用程序,在其中我可以提供从快递到客户的图像。 在开发中,一切正常,但是当我部署到heroku时,它不会显示图像。控制台显示 “无法加载资源:net :: ERR_CONNECTION_REFUSED”。

ImageSlider.js

  

    import React from "react";
    import { Carousel } from "antd";
    
    const ImageSlider = (props) => {
      return (
        <div>
          <Carousel autoplay>
            {props.images.map((image,index) => {
              return (
                <div key={index}>
                  <img
                    src={`http://localhost:5000/${image.filename}`}
                    alt={`product_image-${index}`}
                    style={{ height: "150px",width: "100%" }}
                  />
                </div>
              );
            })}
          </Carousel>
        </div>
      );
    };
    
    export default ImageSlider;
      

index.js

    const express = require("express");
    const app = express();
    const path = require("path");
    const cors = require("cors");
    require("dotenv").config();

    const bodyParser = require("body-parser");
    const cookieParser = require("cookie-parser");

    const config = require("./config/key");

    const mongoose = require("mongoose");
    const connect = mongoose
      .connect(config.MONGO_URI || process.env.MONGO_DB_CONNECTION,{
        useNewUrlParser: true,useUnifiedTopology: true,useCreateIndex: true,useFindAndModify: false,})
      .then(() => console.log("MongoDB Connected..."))
      .catch((err) => console.log(err));

    app.use(cors());

    app.use(bodyParser.urlencoded({ extended: true }));

    app.use(bodyParser.json());
    app.use(cookieParser());

    app.use("/api/users",require("./routes/users"));
    app.use("/api/product",require("./routes/product"));

    app.use(express.static("./server/uploads"));

    if (process.env.NODE_ENV === "production") {
      app.use(express.static("client/build"));
      app.use(express.static("./server/uploads"));

      app.get("*",(req,res) => {
        res.sendFile(path.resolve(__dirname,"../client","build","index.html"));
      });
    }

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

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

我从上传文件夹提供静态文件 我的文件夹结构是AppName/

  /client 
  /server/uploads

服务器和mongo在heroku上运行,因为我可以使用凭据登录

任何帮助都非常重要。

解决方法

您似乎正在尝试从硬编码的URL(http://localhost:5000)加载图像:

<img
   src={`http://localhost:5000/${image.filename}`}
   alt={`product_image-${index}`}
   style={{ height: "150px",width: "100%" }}
/>

http://localhost:5000在您的本地计算机上可用,但是一旦将其部署到Heroku,则应将URL替换为新值(http://example.herokuapp.com)。您也可以尝试使用相对地址,以便在浏览器中自动匹配域:

<img
   src={`/${image.filename}`}
   alt={`product_image-${index}`}
   style={{ height: "150px",width: "100%" }}
/>