簡體   English   中英

生產構建 React 上未加載 Multer 圖像?

[英]Multer Image Not loaded on Production Build React?

我正在使用 MERN 創建簡單的電子商務 我在生產模式下遇到錯誤。 文件上傳到指定文件夾,但不會在前端加載。

服務器.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 上說圖像無法加載檢查圖像=> 前端加載場景的快照,並在圖像元素上進行檢查

現在,當我處於開發模式時,相同的代碼按預期工作並加載圖像。 在此處輸入圖片說明 可能的錯誤是什么,請幫助我。 先感謝您。

您的生產服務器不是用來存儲文件的,因為這會導致服務器資源消耗的增加。 因此它會自動刪除您上傳到生產服務器的任何文件/圖像。

以及為什么要將文件存儲在生產服務器上,只需使用數據庫或文件存儲系統(如 s3 存儲桶)。

我遇到了同樣的錯誤,我所做的只是將上傳文件夾的位置切換到頂部。 構建前端請求任何圖像之前,您要確保所有圖像都可用。

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....')
  })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM