[英]Request body/file empty or not in node.js
我對node.js中的請求有很多疑問。 我有一個放置請求router.put
的路由器(基本上,我想對存儲在MongoDB中的數據進行一些更改)。 我在服務器上存儲了三種不同的東西,即name, price, file(path of file)
,並且將數據存儲在物理硬盤上。
我不想使用patch
因為我本身無法成功完成上傳文件。
為了檢查request.body
依賴項是否為空,我正在使用Object.keys()
,但是我無法將相同的東西應用於request.file
它給出了這個錯誤:
TypeError:無法讀取未定義的屬性“文件名”
這是我的代碼的一部分:順便說一下,在我的js
文件中,我具有所有依賴項和要求,例如multer, body.parser
router.put('/:productId', checkAuth, upload.single('productImage'), (req, res, next) => {
const id = req.params.productId;
var imageName = "";
Product.findById(id)
.exec()
.then(docs => {
if (Object.keys(req.file.filename).length > 0) {
imageName = docs.productImage;
fs.unlink(__rootdir + '\\public\\uploads\\' + imageName, function(err) {
console.log(err);
if (err && err.code == 'ENOENT') {
console.info("File does not exist, will not update");
} else if (err) {
console.info("Error occurred while trying to update");
} else {}
});
}
return Product.findById( {_id: id}).exec();
})
.then(doc => {
if (doc) {
if (Object.keys(req.body.name).length === 0) {doc.name = doct.name;}
else {doc.name = req.body.name;}
if (Object.keys(req.body.price).length === 0) {doc.price = doc.price }
else { doc.price = req.body.price; }
if (Object.keys(req.file.filename).length === 0) {doc.productImage = doc.productImage;}
else {doc.productImage = req.file.filename}
doc.save(err => {
if (err) {
res.send(err);
}
res.status(200).json({
message: 'Product Updated',
request: {
type: 'GET',
url: 'http://localhost:3000//products/' + id
}
});
});
}
});
});
添加的代碼部分:
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const multer = require('multer');
const checkAuth = require('../middleware/check-auth');
const bodyParser = require('body-parser');
router.use(bodyParser.urlencoded());
router.use(bodyParser.json());
const fs = require('fs');
我解決了我的問題。
我沒有使用Object.keys(req.file.filename).length === 0
,而是使用typeof(req.file) !== "undefined"
。 這樣可以確定表單數據(尤其是關於文件上傳)是否存在。 (基本上,檢查上傳區域是否為空)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.