【发布时间】:2021-03-31 11:59:19
【问题描述】:
我正在尝试使用邮递员上传产品,并且我随时提交;它发回带有图像undefined 的所有数据,如下图所示:
我的控制器文件:
const gameRepository = require("../routes/repository")
exports.createGame = async (req, res, next) => {
try {
const PORT = 8000;
const hostname = req.hostname;
const url = req.protocol + '://' + hostname + ':' + PORT + req.path;
const payload = ({
name: req.body.name,
price: req.body.price,
category: req.body.category,
gameIsNew: req.body.gameIsNew,
topPrice: req.body.topPrice,
isVerOrient: req.body.IsVerOrient,
description: req.body.description,
image: url + '/imgs/' + req.path
});
let eachGame = await gameRepository.createGame({
...payload
});
console.log(req.body)
res.status(200).json({
status: true,
data: eachGame,
})
} catch (err) {
console.log(err)
res.status(500).json({
error: err,
status: false,
})
}
}
repository.js:
const Game = require("../models/gameModel");
exports.games = async () => {
const games = await Game.find();
return games;
}
exports.gameById = async id => {
const game = await Game.findById(id);
return game;
}
exports.createGame = async payload => {
const newGame = await Game.create(payload);
return newGame;
}
exports.removeGame = async id => {
const game = await Game.findById(id);
return game;
}
Multer.js:
const multer = require("multer");
const path = require("path");
// checking for file type
const MIME_TYPES = {
'imgs/jpg': 'jpg',
'imgs/jpeg': 'jpeg',
'imgs/png': 'png'
}
// Image Upload
const storage = multer.diskStorage({
destination: (req, file, cb ) => {
cb(null, path.join('../imgs'));
},
filename: (req, file, cb) => {
const name = file.originalname.split('').join(__);
const extension = MIME_TYPES[file.mimetype];
cb(null, name + new Date().toISOString() + '.' + extension);
}
});
module.exports = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 6
},
})
我不确定我哪里出错了,这就是为什么我需要一个外部的眼睛来帮助定位故障的来源。
我有一种感觉,我需要使用body-parser 或者正确导航到图像文件夹,或者多部分表单,我不确定。
【问题讨论】:
-
您提到了 multer 用于文件上传,但您的代码没有显示 multer 中间件。请添加足够的代码以使示例更易于调试。
-
感谢您与我们联系!我将 / 添加到图像中,但仍然得到相同的结果。你建议我删除 const url = req.protocol + '://' + hostname + req.body.path; ?
-
我已添加其他文件中的代码以提供更多信息。
-
您的网址已损坏@GODSWILL 它应该读为
const url = req.protocol + '://' + hostname + ":" + PORT + req.path。您正在使用req.body.path,您可以看到它已损坏,因为它在您的屏幕截图中返回未定义。您应该使用req.path或req.originalUrl取决于您感兴趣的 url 对象的部分 -
谢谢@rags2riches,我需要为 PORT 创建一个新变量吗?
标签: node.js express postman multipartform-data multer