为什么我的router.post()只允许一个操作?

时间:2020-04-21 16:33:54

标签: javascript node.js

我在一个Web项目中工作,后端有问题 我要从前端向后端发送数据,然后进行两项操作:更新目录中的JSON文件,并同时将数据保存在MongoDB中,但只有更新JSON文件才有效,我必须对更新代码进行注释以查看MongoDB中的数据, 这是我的代码:

router.post('/', (req,res)=>{
  console.log(req.body);

  var toSaveDb={
  name:req.body.name,
  age:req.body.age,

 }

 // operation 1 : save the imported data in MongoDB
 let mdata=new MachineData(toSaveDb);
 console.log(mdata);
 mdata.save();


  // operation2 : update the JSON file with imported data 
  fs.writeFile('C:/path/to/file', 
  JSON.stringify(toSaveDb),err=>{
    if(err){console.error(err);return;};
  }); 


 });
module.exports=router;

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

就像fs.writeFile的参数中的错误一样。更改此:

fs.writeFile('C:/path/to/file'), 
  JSON.stringify(toSaveDb),err=>{
    if(err){console.error(err);return;};
  }); 

对此:

fs.writeFile("C:/path/to/file", JSON.stringify(toSaveDb), (err) => {
  if (err) {
    console.error(err);
    return;
  }
});

现在正确了,Prettier

相关问题