【问题标题】:Problems with displaying images from MongoDB using Multer on ReactJS在 ReactJS 上使用 Multer 从 MongoDB 显示图像的问题
【发布时间】:2019-04-06 05:03:06
【问题描述】:

基本上总结我的问题:我有一些图像要显示,它显示在 localhost:5000 上,状态为 200,我的 Express 服务器正在运行,当涉及到 localhost:3000 时,即我的 React 开发服务器,我提出了一个请求使用 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: "����..."

【问题讨论】:

标签: node.js reactjs mongodb express multer-gridfs-storage


【解决方案1】:

解决方案: 所以我更多地使用代码,我忘记了它存在于我客户端的 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 并向 ExpressJS 发送 GET 请求,从而加载图片!

【讨论】:

    猜你喜欢
    • 2017-12-22
    • 1970-01-01
    • 2022-12-14
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 2018-01-27
    • 2021-01-24
    • 2021-02-04
    相关资源
    最近更新 更多