Product create - Test 我能够创建一个类别,但是在创建产品时,我使用邮递员对其进行了测试,并显示错误:“”,然后我添加了要求显示所有字段的代码。它们都是,除了消息不断弹出错误:“所有字段都是必需的”。我已经尝试了以下所有解决方案,但是没有一个对我有用吗?
const formidable = require("formidable");
const _ = require("lodash");
const fs = require("fs");
const Product = require("../models/product");
const { errorHandler } = require("../helpers/dbErrorHandler");
exports.productById = (req, res, next, id) => {
Product.findById(id).exec((error, product) => {
if (error || !product) {
return res.status(400).json({
error: "Product not found"
});
}
req.product = product;
next();
});
};
exports.read = (req, res) => {
req.product.photo = undefined;
return res.json(req.product);
};
exports.create = (req, res) => {
let form = new formidable.IncomingForm();
form.keepExtensions = true;
form.parse(req, (error, fields, files) => {
if (error) {
return res.status(400).json({
error: "Image could not be uploaded"
});
}
// check for all fields
const {
name,
description,
price,
category,
quantity,
shipping
} = fields;
if (
!name ||
!description ||
!price ||
!category ||
!quantity ||
!shipping
) {
return res.status(400).json({
error: "All fields are required"
});
}
let product = new Product(fields);
// 1kb = 1000
// 1mb = 1000000
if (files.photo) {
// console.log("FILES PHOTO: ", files.photo);
if (files.photo.size > 1000000) {
return res.status(400).json({
error: "Image should be less than 1mb in size"
});
}
product.photo.data = fs.readFileSync(files.photo.path);
product.photo.contentType = files.photo.type;
}
product.save((error, result) => {
if (error) {
return res.status(400).json({
error: errorHandler(error)
});
}
res.json(result);
});
});
};
exports.remove = (req, res) => {
let product = req.product;
product.remove((error, deletedProduct) => {
if (error) {
return res.status(400).json({
error: errorHandler(error)
});
}
res.json({
"message": "Product deleted successfully"
});
});
};
答案 0 :(得分:0)
为什么不控制台登录每个要求,例如
exports.productById = (req, res, next, id) => {
console.log(req.body);
};
exports.read = (req, res) => {
console.log(req.body);
};
exports.create = (req, res) => {
console.log(req.body);
};
exports.remove = (req, res) => {
console.log(req.body);
};
您将清楚了解后端是否实际收到您的请求。
答案 1 :(得分:0)
if (
!name ||
!description ||
!price ||
!category ||
!quantity ||
!shipping
) {
return res.status(400).json({
error: "All fields are required"
});
}
您从邮递员发送了错误的运输邮件,显然它将返回400状态,使它成为
if (
!name ||
!description ||
!price ||
!category ||
!quantity ||
shipping!== true || shipping !==false //something like that(or use something from formidable)
) {
return res.status(400).json({
error: "All fields are required"
});
}
```
答案 2 :(得分:0)
您的问题是在邮递员中设置内容类型。您将表单数据发送到服务器,但服务器未对它进行解码。默认情况下,您的服务器获取x-www-form-urlencoded,如果在x-www-form-urlencoded上设置邮递员,则问题就不存在了。 您必须使用表格数据上传文件