简体   繁体   English

在node.js中请求正文/文件是否为空

[英]Request body/file empty or not in node.js

I have quite issues with the requests in node.js. 我对node.js中的请求有很多疑问。 I have a router that put request router.put (basically, I want to make some changes on a data that I stored in MongoDB). 我有一个放置请求router.put的路由器(基本上,我想对存储在MongoDB中的数据进行一些更改)。 I am storing three different things which are name, price, file(path of file) on the server, and I am storing the data on the physical hard drive. 我在服务器上存储了三种不同的东西,即name, price, file(path of file) ,并且将数据存储在物理硬盘上。

I did not want to use patch because I could not succeed the upload file by itself. 我不想使用patch因为我本身无法成功完成上传文件。

In order to check the request.body dependencies empty or not, I am using Object.keys() , but I cannot apply the same thing to request.file 为了检查request.body依赖项是否为空,我正在使用Object.keys() ,但是我无法将相同的东西应用于request.file

It gives this error: 它给出了这个错误:

TypeError: Cannot read property 'filename' of undefined TypeError:无法读取未定义的属性“文件名”

And this is part of my code: By the way, in my js file I have all dependencies & requirements like multer, body.parser 这是我的代码的一部分:顺便说一下,在我的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
                    }
                });
            });
        }        
    });
 });

Added code part: 添加的代码部分:

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

I solved my problem. 我解决了我的问题。

Instead of using Object.keys(req.file.filename).length === 0 , I used typeof(req.file) !== "undefined" . 我没有使用Object.keys(req.file.filename).length === 0 ,而是使用typeof(req.file) !== "undefined" Doing like this can identify the form-data (especially about file uploading) exist or not. 这样可以确定表单数据(尤其是关于文件上传)是否存在。 (Basically, checks the upload area empty or not) (基本上,检查上传区域是否为空)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM