基本上可以概括我的问题:我有一些要显示的图像,它显示在状态为200的localhost:5000上,我的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: "����..."
答案 0 :(得分:0)
解决方案: 因此,我更多地使用了代码,而我忘记了它存在于客户端的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 请求,从而加载图片!