Node.js “错误”;req.body.fileToString不是一个函数;
使用nodejs和mongodb文件上载 这是我的POST APINode.js “错误”;req.body.fileToString不是一个函数;,node.js,mongodb,mongoose,fs,multer,Node.js,Mongodb,Mongoose,Fs,Multer,使用nodejs和mongodb文件上载 这是我的POST API router.post('/create',multer({ storage : storage}).any(), (req, res) => { var sample = fs.readFileSync('./uploads/'+req.files[0].filename,'utf8'); var tc = new Testcase({ name: req.body.name,
router.post('/create',multer({ storage : storage}).any(), (req, res) => {
var sample = fs.readFileSync('./uploads/'+req.files[0].filename,'utf8');
var tc = new Testcase({
name: req.body.name,
upload: req.files[0].filename ,
run: req.body.fileToString(function() {
let arr = sample.split(/\r?\n/);
arr.forEach((step , idx)=> {
if(step.includes("step")){
console.log(step);
return step;
}
});
}
),
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,
});
console.log(req.files[0].filename);
tc.save((err, doc) => {
if (err) { res.status(401).send("error") }
else {
res.status(200).send(doc)
}
});
});
当我使用postman发布包含文件的新行时,会出现以下错误:
“消息”:“req.body.fileToString不是函数”
请问我做错了什么这是错的:
run: req.body.fileToString(function() {
let arr = sample.split(/\r?\n/);
arr.forEach((step , idx)=> {
if(step.includes("step")){
console.log(step);
return step;
}
});
您不能将参数发送到
req.body.fileToString
,因为它是来自客户端的数据,而不是函数
router.post('/create',multer({ storage : storage}).any(), (req, res) => {
var sample = fs.readFileSync('./uploads/'+req.files[0].filename,'utf8');
var stepss = function(callback) {
let arr = sample.split(/\r?\n/);
arr.forEach((step , idx)=> {
if(step.includes("step")){
console.log(step);
stepstr = JSON.stringify(step);
callback(null, stepstr);
}
});
}
var tc = new Testcase({
name: req.body.name,
//upload: url + "/uploads/" + req.files[0].filename ,
upload: req.files[0].filename ,
run: stepss,
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,
});
//const file = req.file;
console.log(req.files[0].filename);
tc.save((err, doc) => {
if (err) { res.status(401).send("error") }
else {
res.status(200).send(doc)
}
});
});
但是现在,当我添加一些东西时,变量run的内容正是我编写的函数,而不是它的结果:
"run": "function(callback) {\r\n let arr = sample.split(/\\r?\\n/);\r\n arr.forEach((step , idx)=> {\r\n if(step.includes(\"step\")){\r\n console.log(step);\r\n stepstr = JSON.stringify(step);\r\n callback(null, stepstr);\r\n\r\n }\r\n });\r\n }",
如何将函数的返回值存储到变量中?关于如何将函数结果存储在变量“run”中,您有什么解决方案吗?我不明白您想做什么我正在使用multer将文件上载到数据库,我正在尝试制作一个读取我正在加载的文件的函数,搜索包含单词“step”的行并将结果存储到变量“run”中,函数fileToString是功能性的,它提供了我想要的。。我想在创建新行时将函数的结果存储在变量中