I have built a website like a blog post. The image is being uploaded to MongoDB and has not been displayed on the website. I have checked whether the image is rendered using Postman; the image has been displayed and all the data is displayed. but the image is not displayed on the the website.
mongodb.js
import express from "express";
import mongoose from "mongoose";
import multer from 'multer';
import path from "path";
import dotenv from "dotenv";
import { title } from "process";
import './dbtest.js';
import cors from "cors";
dotenv.config();
const app = express();
const port = 8000;
mongoose.connect(process.env.MongoDb_Connection_string,{
ssl: true,
});
const postSchema = new mongoose.Schema({
title:String,
content:String,
image:String
});
const Post = mongoose.model('posts',postSchema);
const storage = multer.diskStorage({
destination:function(req,file,cb){
cb(null,'uploads/');
},
filename:function(req,file,cb){
cb(null,Date.now()+path.extname(file.originalname));
}
})
const upload = multer({storage:storage});
app.use('/uploads',express.static('uploads'));
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({extended:true}));
app.use('/uploads', express.static('uploads'));
app.post('/posts',upload.single('image'),async(req,res)=>{
try{
console.log(req.file);
const{title,content} = req.body;
const image = req.file ? `uploads/${req.file.filename}` : null;
const newPost = new Post({title,content,image});
await newPost.save();
res.status(201).send('Post created sucessfully');
}catch(error){
res.status(500).send('Error creating post');
console.error('Error creating post:', error);
}
});
app.get('/posts', async (req, res) => {
try {
const posts = await Post.find();
res.status(200).json(posts.map(post=>({
...post._doc,
image: post.image ? `http://localhost:8000/${post.image}` : null
})));
} catch (error) {
res.status(500).send('Error fetching posts');
console.error('Error fetching posts:', error);
}
});
app.listen(port,()=>{
console.log(`server is running on http://localhost:${port}`)
})
HomePage.js
import React, { useState,useEffect } from "react";
import { Link } from "react-router-dom";
import { Showcntnt } from "./content";
import axios from 'axios'
export function HomePage({ post }) {
const [postList, setPostList] = useState(post);
useEffect(() => {
axios.get("http://localhost:3000/posts")
.then(response => setPostList(response.data))
.catch(err => console.log(err))
}, []);
return (
<div>
<h1 className="text-4xl font-bold text-center text-white mb-8">Welcome to Our Content Hub</h1>
{/* Featured Section */}
<div className="mb-12">
<h2 className="text-2xl font-bold text-white mb-4">Featured Content</h2>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="relative overflow-hidden rounded-lg shadow-lg">
<img src="/giphy.gif" alt="Featured 1" className="w-full h-48 object-cover" />
<div className="absolute bottom-0 left-0 right-0 px-4 py-2 bg-gray-800 opacity-70">
<h3 className="text-xl text-white font-bold">Featured Item 1</h3>
</div>
</div>
<div className="relative overflow-hidden rounded-lg shadow-lg">
<img src="/giphy2.gif" alt="Featured 2" className="w-full h-48 object-cover" />
<div className="absolute bottom-0 left-0 right-0 px-4 py-2 bg-gray-800 opacity-70">
<h3 className="text-xl text-white font-bold">Featured Item 2</h3>
</div>
</div>
<div className="relative overflow-hidden rounded-lg shadow-lg">
<img src="/giphy3.gif" alt="Featured 3" className="w-full h-48 object-cover" />
<div className="absolute bottom-0 left-0 right-0 px-4 py-2 bg-gray-800 opacity-70">
<h3 className="text-xl text-white font-bold">Featured Item 3</h3>
</div>
</div>
</div>
</div>
{/* User-generated Content */}
<h2 className="text-2xl font-bold text-white mb-4">Latest Posts</h2>
{post.length === 0 ? (
<div className="text-center text-gray-400">
<p>No content available yet. Start by creating some!</p>
<Link to="/createcontent" className="mt-4 inline-block bg-green-500 text-white font-bold py-2 px-4 rounded hover:bg-green-600 transition duration-300">Create Content</Link>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{post.map((item, index) => (
<Showcntnt
key={index}
id={index}
photo={item.image || "/uploads/placeholder.jpg"}
title={item.title}
content={item.content}
/>
))}
</div>
)}
</div>
);
}
content.js
export function Showcntnt({ photo, title, content }) {
return (
<div className="bg-gray-800 rounded-lg shadow-md overflow-hidden transition duration-300 transform hover:scale-105">
<img
src={photo.startsWith('http') ? photo : `http://localhost:8000/${photo}`}
alt={title}
className="w-full h-48 object-cover"
/>
<div className="p-4">
<h2 className="font-bold text-xl mb-2 text-white">{title}</h2>
<p className="text-gray-400">{content.substring(0, 100)}...</p>
<button className="mt-4 bg-green-500 text-white font-bold py-2 px-4 rounded hover:bg-green-600 transition duration-300">
Read More
</button>
</div>
</div>
);
}