gpt4 book ai didi

How to render images from backend to frontend in mern stack(如何在Mern堆栈中将图像从后台渲染到前端)

转载 作者:bug小助手 更新时间:2023-10-28 13:16:46 25 4
gpt4 key购买 nike



Here, I'm trying to render images that are in backend/uploads/images.`

在这里,我正在尝试渲染后端/上传/图像中的图像。


this is my backend server.js file

这是我的后端server.js文件




const express = require("express");
require("dotenv").config();
const cors = require("cors");
const { v4: uuidv4 } = require("uuid");
const app = express();
const postRoute = require("./routes/postRoute");
const userRoute = require("./routes/userRoute");
const DbConnection = require("./db/db");

DbConnection();
app.use(cors());
app.use(express.json());
app.use(express.static("uploads/images"));

app.get("/", (req, res) => {
res.send("Home server");
});

app.use("/api", postRoute);
app.use("/api/users", userRoute);
app.listen(process.env.PORT || 5000, () => {
console.log("Server started");
});




`

`


this is my ui where i want to pull the image as title("hello") and content("sadsaassa") is being pulled from mongodb.
enter image description here

这是我的用户界面,我想把标题(“Hello”)和内容(“sadsaassa”)从MongoDB拉出来。


this is how i tried to pull the image
<img
src={../../../../backend/uploads/images/${detailedArticle?.imageUrl}}
/>
Can anyone help me?

这是我试图拉图像有人能帮我吗?


更多回答
优秀答案推荐

Since Nodejs and Reactjs are running in different server, you have to access images over http something like this..

由于NodeJS和Reactjs运行在不同的服务器上,因此您必须通过http访问图像,如下所示。


http://localhost:5000/{image}.png


You can not access it from the local directory as you are saving the image using NodeJS.

您无法从本地目录访问,因为您正在使用NodeJS保存镜像。


If you are trying to access on local machine where your node server is also running then use

如果您尝试在节点服务器也在运行的本地计算机上访问,则使用



http://localhost:3000/server/public/upload/{image}



If you are trying to access the image from already deployed node application then use

如果您尝试从已部署的节点应用程序访问映像,则使用



http://abchost:3000/server/public/upload/{image}




Create an API in backend:

在后台创建API:


app.use('/images', express.static('uploads/images'));

and frontend code is:

前端代码为:


<img src={`/images/${product.image}`} alt={product.name} />

更多回答

can you help me with it?

你能帮我搬一下吗?

Can you print detailedArticle.imageUrl here? It should be the file name.

你能在这里打印DetailedArticle.ImageUrl吗?它应该是文件名。

7c1d83fbe2bc6593cebab98c714e6da8.jpeg it is like this

7c1d83fbe2bc6593ceBab98c714e6da8.jpeg是这样的

I tried this but didnt work <img src={http://localhost:8000/${detailedArticle.imageUrl}} />

我试过了,但不起作用

Can you please let me know your node URL and exact path of the assets folder where your images are store towards nodeJS.

您能告诉我您的节点URL和您的图片存储到NodeJS的Assets文件夹的确切路径吗?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com