Multer Image 未在 Production Build React 上加载?

Multer Image Not loaded on Production Build React?

我正在使用 MERN 创建简单的电子商务我在生产模式下遇到错误。文件上传到指定文件夹,但前端没有加载。

Server.js

import path from 'path'
import express from 'express'
import dotenv from 'dotenv'

const __dirname = path.resolve()

if (process.env.NODE_ENV === 'production') {
  app.use(express.static(path.join(__dirname, '/frontend/build')))

  app.get('*', (req, res) =>
    res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'))
  )
} else {
  app.get('/', (req, res) => {
    res.send('Api running....')
  })
}

app.use('/uploads', express.static(path.join(__dirname, '/uploads')))

上传路线和代码

import path from 'path'
import express from 'express'
import multer from 'multer'

const router = express.Router()
const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, '/uploads')
  },
  filename(req, file, cb) {
    cb(
      null,
      `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`
    )
  },
})

function checkFileType(file, cb) {
  const filetypes = /jpg|jpeg|png/
  const extName = filetypes.test(path.extname(file.originalname).toLowerCase())
  const mimeType = filetypes.test(file.mimetype)

  if (extName && mimeType) {
    return cb(null, true)
  } else {
    cb('Images only with jpg, jpeg, png ')
  }
}

const upload = multer({
  storage,
  fileFilter: function (req, file, cb) {
    checkFileType(file, cb)
  },
})

router.post('/', upload.single('image'), (req, res) => {
  res.send(`/${req.file.path}`)
})

export default router

当我检查它在 src 上显示的文件时,图像无法加载检查图像=>

现在,当我处于开发模式时,相同的代码会按预期工作并加载图像。 可能有什么错误请帮助我。 提前致谢。

您的生产服务器不是用于存储文件的,因为这会导致服务器资源消耗增加。因此它会自动删除您上传到生产服务器的任何 files/images。

为什么要在生产服务器上存储文件,只需使用数据库或文件存储系统,如 s3 存储桶。

我遇到了同样的错误,我所做的只是将上传文件夹的位置切换到顶部。您要确保在前端的 build 从中请​​求任何图像之前所有图像都可用。

import path from 'path'
import express from 'express'
import dotenv from 'dotenv'

const __dirname = path.resolve()
// Put it here
app.use('/uploads', express.static(path.join(__dirname, '/uploads')))

if (process.env.NODE_ENV === 'production') {
  app.use(express.static(path.join(__dirname, '/frontend/build')))

  app.get('*', (req, res) =>
    res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'))
  )
} else {
  app.get('/', (req, res) => {
    res.send('Api running....')
  })
}