“响应保存”;“未定义”;在我的文件node.js中

“响应保存”;“未定义”;在我的文件node.js中,node.js,httprequest,Node.js,Httprequest,我知道node.js使用异步行为。我试图在文件系统中保存响应的原因是“未定义”。实际上,在响应到来之前,该文件将保存“未定义”数据 这是我的密码 request(options, function (error, response, body){ if(!error){ console.log(body); //gives the response successfully fs.writeFile("E:/FirebaseNotif/testfile", bo

我知道node.js使用异步行为。我试图在文件系统中保存响应的原因是“未定义”。实际上,在响应到来之前,该文件将保存“未定义”数据

这是我的密码

 request(options, function (error, response, body){
 if(!error){
    console.log(body);       //gives the response successfully
     fs.writeFile("E:/FirebaseNotif/testfile", body.notification_key,  function(err) {
if(err) {
    return console.log(err);
}

console.log("The file was saved!");     //saves but with an "undefined" data
});         
 }else{
    console.log('this is false');
 }

 });

如何处理这种异步行为

问题请求以字符串形式返回响应,因此正文变量包含字符串值,而不是JSON。您需要将响应转换为JSON并使用变量

在收到响应后尝试以下操作

console.log(body);
const data = JSON.parse(body);
fs.writeFile('testfile', data.notification_key, function (err) {
  if (err) {
    return console.log(err);
  }

  console.log('The file was saved!');
});

您可以通过在项目的根目录中创建“message.txt”并将
路径更改为
“message.txt”
,然后检查它是否可以在message.txt中写入数据,来验证函数是否正常工作