【问题标题】:Request body/file empty or not in node.js在 node.js 中请求正文/文件为空或不为空
【发布时间】:2018-09-06 21:50:31
【问题描述】:

我对 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');

【问题讨论】:

  • 您似乎没有使用 Content-type: form-data 配置您的标头,您能否将您正在执行请求的代码的客户端部分提供给您?
  • @vitomadio我正在更新帖子。我正在添加像body.parser 这样的部分
  • 确保在 html 文件的表单标签中添加 enctype="multipart/form-data"。
  • @vitomadio 我正在使用邮递员对其进行测试。在邮递员中,我认为没有这样的选择

标签: node.js mongodb rest api request


【解决方案1】:

我解决了我的问题。

我没有使用Object.keys(req.file.filename).length === 0,而是使用了typeof(req.file) !== "undefined"。这样做可以识别表单数据(尤其是关于文件上传)是否存在。 (基本上,检查上传区域是否为空)

【讨论】:

    猜你喜欢
    • 2013-07-09
    • 1970-01-01
    • 2021-03-20
    • 2019-04-12
    • 2023-03-28
    • 2021-08-29
    • 2019-07-25
    • 2015-06-27
    • 2020-06-06
    相关资源
    最近更新 更多