在 ReactJS 上使用 Multer 显示来自 MongoDB 的图像时出现问题

Problems with displaying images from MongoDB using Multer on ReactJS

基本上总结一下我的问题:我有一些图像要显示,它显示在 localhost:5000 上,状态为 200,我的 Express 服务器是 运行,当涉及到 localhost:3000 时即我的 React Development Server,我使用 Axios 发出了一个请求,它确实给了我乱码,我根本不知道如何处理它。

反应代码:

componentDidMount() {
    axios.get('/filesuploaded/video_______82395d6a5af4e98fb8efca56f0ae3c1b_____.jpeg')
         .then(Response => console.log(Response))
         .catch(err => console.log(err));
  }

快递编码:

route.get('/:filename' , (req , res) => {
    GridFS.files.findOne({filename: req.params.filename} , (err , file) => {
        const readstream = GridFS.createReadStream(file.filename);
        readstream.pipe(res);
    })
});

随机乱码:

{data: "����..."

解决方案: 所以我更多地使用代码,我忘记了它存在于我的客户端 package.json 中,我已经充分利用它并重写了我的服务器端代码,而没有在任何地方使用 multer。

Package.json:

"proxy": "http://localhost:5000" //This helps React communicate with ExpressJS through ports.

服务器端配置:

const route           = require('express').Router();
const mongoose        = require('mongoose');
const GridFS          = require('gridfs-stream');

//Route for getting files
route.get('/file/:id' , (req , res) => {

  //Setting Up GridFS-Stream
  const db          = mongoose.connection.db;
  const MongoDriver = mongoose.mongo;
  const gfs         = new GridFS(db , MongoDriver);

  const readstream = gfs.createReadStream({
    _id: req.params.id,
  });

   //Reading to Response
   readstream.pipe(res);
});

module.exports = route;

前端配置:


import React, { Component } from 'react'

export default class Files extends Component {

//Render Method
  render() {
    return (
      <div>
        <img src = {window.location.pathname} alt = "something" />
      </div>
    )
  }
}

此处的 window.location.pathname 将转换为 /file/:id 并发送 GET 请求 ExpressJS,因此加载图像!