首页 > 解决方案 > 如何在 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)
})

标签: node.jsreactjsmulter

解决方案


推荐阅读