I'm looking to serve some images I have stored in my GridFS database to my Next.js project. Sometimes the images load in development (sometimes they don't), however they never load in production. I'm using gridfs-stream
to serve the images.
On the client side the image is called like this:
<img src={`/api/image?id=${filename}`} />
And on the server it serves the image like this:
import mongoose from 'mongoose';
import nc from 'next-connect';
const Grid = require('gridfs-stream');
const conn = mongoose.createConnection(gridFSURI);
let gfs;
conn.once('open', () => {
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('files');
});
const handler = nc();
handler.get((req, res) => {
gfs.files.findOne({ filename: req.query.id }, (err, file) => {
if (!file || file.length === 0) {
return res.status(404).json({
err: 'No file exists'
});
} else {
const readstream = gfs.createReadStream(file.filename);
readstream.pipe(res);
}
});
})
export const config = {
api: {
bodyParser: false,
},
};
export default handler;
Should these images be served through getServerSideProps
?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…