1

基本上总结一下我的问题:我有一些图像要显示,它显示在 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: "����..."
4

1 回答 1

0

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

包.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请求,从而加载图像!

于 2019-04-08T05:33:13.550 回答