簡體   English   中英

如何在 React 中顯示圖像,這些圖像作為文件下載並保存在服務器上的文件夾中,文件路徑存儲在我的數據庫中?

[英]How do I Display Images in React which are downloaded as Files & saved in a Folder on the Server with the Filepath stored in my Database?

簡短設置、問題和代碼摘要

設置

React.js、Node.js/Express.js 和 PostgreSQL。

我刮了一本書的ImageUrl,下載並使用Node.js將其存儲在圖像文件夾中的文件中,並將文件路徑存儲在我的postgreSQL數據庫中,我想在我的React前端的<img />標簽中獲取並顯示圖像.

問題

The Image I Fetch from my Database through my API doesn't get displayed, eventhough I can console.log the Image Object in the devtool-console and even make a succesful Postman request with the Image-Object as JSON response. 此外,如果我將 go 轉到 localhost:3001/image-193x278.png,我什至可以顯示圖像。 我的<img />標簽甚至在 devtools (images\image-193x278.png) 中顯示了正確的 Img src 屬性

在 devtool-console 我收到以下錯誤: GEThttp://localhost:3002/images/image-193x278.png [HTTP/1.1 404 Not Found 0ms]

(注意:我的前端在 localhost 3002 上運行,而我的服務器和前端與 3001 上的代理同時運行,但這不是導致問題的原因)

代碼

反應代碼

const [image, setImage] = useState([]);

  useEffect(() => {

    async function fetchData() {
      const response = await fetch('http://localhost:3001/test', {
        method: 'GET',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        }
      })
      const data = await response.json();
      console.log(data);
      setImage(data);
    }
    fetchData();

  }, []);

我試圖讓它以兩種不同的方式顯示:

<img className={css(styles.Image)} src={image.test_images} alt="" />

{image.map((img) => 
<img className={css(styles.Image)} src={img.test_images} alt="" />)}

服務器端

app.get('/test', async (req, res) => {
    try {
        const image = await testdb.query('SELECT * FROM test_table');
        res.json(image.rows);
    } catch (err) {
        console.error(err);
    }
})

我提供 Express Static 文件

app.use(express.static('images'));

我什至嘗試了另外兩個變種以防萬一

app.get('/test', express.static(__dirname + '../images'));
app.use(express.static('../images'));

仍然沒有成功。 我希望我能盡可能地讓自己被理解,我會非常感謝每一個幫助我的人。

問題在於您的 static 文件夾。 static 文件將在localhost:3002/:filename可用。

如果你想讓它在/images路徑下工作,那么你可以將路徑添加到 static 聲明中,例如

app.use('/images', express.static('images'))

然后你可以點擊localhost:3002/images/:filename

您可以在此處找到文檔: https://expressjs.com/en/starter/static-files.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM