Basically to summarize my problem: I have some image to be displayed and it's displayed on localhost:5000 with status 200 where my Express server is running and when it comes to localhost:3000 i.e. my React Development Server, I made a request using Axios and it does give me gibberish and I don't know how to handle it at all.
React Code:
componentDidMount() {
axios.get('/filesuploaded/video_______82395d6a5af4e98fb8efca56f0ae3c1b_____.jpeg')
.then(Response => console.log(Response))
.catch(err => console.log(err));
}
Express Code:
route.get('/:filename' , (req , res) => {
GridFS.files.findOne({filename: req.params.filename} , (err , file) => {
const readstream = GridFS.createReadStream(file.filename);
readstream.pipe(res);
})
});
Random Gibberish:
{data: "����..."
SOLUTION: So I played around more with the code and I had forgotten that this existed in my package.json of my client side and I have used it to full potential and rewrote my server side code without using multer anywhere.
Package.json:
"proxy": "http://localhost:5000" //This helps React communicate with ExpressJS through ports.
Server Side Config:
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;
Front End Config:
import React, { Component } from 'react'
export default class Files extends Component {
//Render Method
render() {
return (
<div>
<img src = {window.location.pathname} alt = "something" />
</div>
)
}
}
Here the window.location.pathname will translate to /file/:id and send a GET request to ExpressJS, hence loading the image!