\"data\" 参数必须是字符串类型或 Buffer、TypedArray 或 DataView 的实例收到未定义

问题描述

你好,我正在尝试用 nodejs 编写一个文件,我给它一个目录以将其保存在 mongodb 数据库中 但我收到错误 “数据”参数必须是字符串类型或 Buffer、TypedArray 或 DataView 的实例。收到未定义 当我尝试写入文件

这是我的API

router.post('/create2',(req,res) => {

    
    var tc = new Testcase({
        name: req.body.name,upload: fs.writeFile('./uploads/'+req.body.name+'.robot',req.body.step1,function (err) {
            if (err) throw err;               console.log('Results Received');
          }),run : req.body.run,modify: req.body.modify,delete: req.body.delete,step1: req.body.step1,step2: req.body.step2,step3: req.body.step3,step4: req.body.step4,step5: req.body.step5,step6: req.body.step6,step7: req.body.step7,});
    tc.save((err,doc) => {
        if (!err) { res.send(doc); }
        else { console.log('Error in Employee Save :' + JSON.stringify(err,undefined,2)); }
    });
});

这是我的测试用例架构:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const testcaseSchema = new Schema({
    name: {type : String,required : true,unique : true},upload: String,run: String,modify: String,delete: String,step1: String,step2: String,step3: String,step4: String,step5: String,step6: String,step7: String,checked: { type: Boolean,default: false }

    
    });
module.exports = mongoose.model('testcase',testcaseSchema,'testcases');

解决方法

如果 req.body.step1undefined,这说明了错误,因为这不是您可以传递给 fs.writefile() 的有效信息。我可以想到 req.body.step1 会是 undefined 的几个原因。

  1. POST 未在数据正文中包含 step1 字段。
  2. 帖子中的内容类型不正确,与帖子中数据正文的格式不匹配。
  3. 您用于将 POST 正文解析为 req.body 的中间件未正确配置或未在此路由之前运行,或者您根本没有安装它。