我的MERN
堆栈应用程序有问题。根express应用程序中的图像显示在开发环境中,但是当我在heroku
上部署应用程序时,图像拒绝显示。我使用app.use(express.static('images'))
静态提供了图像,但它仍未在生产环境中显示。这是快递后端上的index.js
文件。
app.use('/images', express.static(path.join(__dirname, 'images')));
app.use('/images/profilephotos', express.static(path.join(__dirname, 'images/profilephotos')));
app.use('/images/productimages', express.static(path.join(__dirname, 'images/productimages')));
app.use('/images/postimages', express.static(path.join(__dirname, 'images/postimages')));
app.use('/images/coverimages', express.static(path.join(__dirname, 'images/coverimages')));
这是我要求前端有反应的图像的方式。
if(posts) {
renderPosts = posts.map(post => {
return (
<div key={post._id} className="homeposts__box">
{post.image ? <img className="homeposts__img" src={'http://' + window.location.hostname + '/' + post.image} alt="Article image" /> : null }
<div className="homeposts__contentbox">
<h6>Article</h6>
<h3><NavLink to={'/blog/' + post._id}>{post.title}</NavLink></h3>
{post.tags ? post.tags.map(tag => <span className="homeposts__tags">{tag}</span>) : null}
<p>{post.body}<NavLink to={'/blog/' + post._id}>Read More</NavLink></p>
<span>by <span style={{fontWeight: 'bold'}}> {post.firstName + ' ' + post.lastName} </span> • <Moment format="MMM D YYYY">{post.createdAt}</Moment> • Comments: <span style={{ color: '#082e40'}}>{post.comments}</span></span>
</div>
</div>
)
})
} else {
renderPosts = <Skeleton count={4}/>
}
我也尝试过在我希望工作的相对路径上使用
if(posts) {
renderPosts = posts.map(post => {
return (
<div key={post._id} className="homeposts__box">
{post.image ? <img className="homeposts__img" src={post.image} alt="Article image" /> : null }
<div className="homeposts__contentbox">
<h6>Article</h6>
<h3><NavLink to={'/blog/' + post._id}>{post.title}</NavLink></h3>
{post.tags ? post.tags.map(tag => <span className="homeposts__tags">{tag}</span>) : null}
<p>{post.body}<NavLink to={'/blog/' + post._id}>Read More</NavLink></p>
<span>by <span style={{fontWeight: 'bold'}}> {post.firstName + ' ' + post.lastName} </span> • <Moment format="MMM D YYYY">{post.createdAt}</Moment> • Comments: <span style={{ color: '#082e40'}}>{post.comments}</span></span>
</div>
</div>
)
})
} else {
renderPosts = <Skeleton count={4}/>
}
[我需要知道如何从我的快速后端在生产服务器上静态提供这些图像。
您能否分享示例数据,如post.image中的内容。
此外,如果您要像下面那样定义其根目录,则不必为每个子文件夹都定义静态服务器。
app.use('/images', express.static(path.join(__dirname, 'images')));
src={'http://' + window.location.hostname + '/' + post.image}
代替
src={`/${post.image}`}
这应该可以工作,并且您的post.image
中应该有/images
条,或者您也需要将其附加到上述src中