node.js - 如何在 React js 前端使用 multer 显示存储在节点 js 服务器中的图像?
问题描述
我已将我的图像保存在我的 mongodb 数据库中:
"_id": "6083db1b285ba32b60206bb3",
"imgUrl": "http:localhost:8000/image/image_1619254043731.JPG",
__v": 0
Nodejs 后端位于 8000 端口,React js 位于 3000 端口。当我尝试使用 img 标签和 src 属性显示图像时,我已经放置了从数据库中获取的“imgUrl”。但它不显示图像。但是当我将 imgUrl(http:localhost:8000/image/image_1619254043731.JPG) 粘贴到单独的选项卡中时,它会显示图像。我不知道问题是什么。
我的客户端代码:
const App = () => {
const [data, setdata] = useState([])
const getData=async()=>{
const res= await axios.get('http://localhost:8000/products')
setdata(res.data)
}
return(
<>
<button onClick={getData}>Get Data</button>
{data.map((item)=>{
return(
<>
<p>{item._id}</p>
<img src={item.imgUrl} alt="hi"/>
</>
)
})}
</>
)
}
我的服务器端代码:
const storage= multer.diskStorage({
destination: './uploads/images',
filename: (req, file, cb)=>{
return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`)
}
})
const upload= multer({
storage,
limits: {fileSize: 100000}
})
app.use(cors())
app.use('/image', express.static(path.join(__dirname, '/uploads/images')))
app.get('/products', async (req, res)=>{
const data= await Database.find({})
res.status(200).json(data);
})
app.post('/uploads', upload.single('image'),async (req, res)=>{
const imgUrl= `http:localhost:8000/image/${req.file.filename}`
const data= new Database({imgUrl})
await data.save()
res.send(data)
})
解决方案
推荐阅读
- c++ - 有没有办法完全禁用 gdb 输出?
- powershell - 输出表 w。自定义属性显示错误计数?
- ios - iPhone 11 和/或 iOS 13 的 iBeacon 监控/测距问题
- css - 希望将滑块中的图像垂直对齐到中间
- ubuntu - Apache Guacamole 登录无效
- c# - 如何修复此错误(System.Windows.Forms.DataGridViewCell.Value.get 返回 null。)
- javascript - 在javascript中从另一个列表中删除一个列表的内容时出现问题
- mongodb - 由于子数组展开后重复,Mongo 父总和错误
- java - 如何让我的程序等到任务完成后再继续?
- python - 给定小数位数的平方根近似值