首页 > 解决方案 > node.js如何使用fs来接收get api结果

问题描述

我是 node.js 的新手。在这里,我正在尝试使用收到的结果(response.body)创建一个 txt 文件。但它只是打印一个异常。需要你的帮助。

function fetch(){

const got = require('got');

got('https://www.google.com', { json: true }).then(response => {

    console.log(response.body);
    temp = response.body;

}).catch(error => {
    console.log(error.response.body);
});
};


setInterval(fetch, 10000);

const fs = require('fs');
fs.write('demo3.txt', response.body, { flag: "a"}, function(err){

if(err){
    return console.log(err);
}
});

标签: javascriptnode.jsrest

解决方案


由于您是 nodeJS 的新手,因此您需要了解回调函数的概念。这里的'got'是一个回调函数。与其他类型的脚本不同,NodeJs 不会等待 fetch 完成,而是继续前进并执行剩余的语句。您的代码有一些错误。

  1. 变量“temp”、“response”的范围。-- 在执行 fs.write 时,response.body 保持未定义和未声明。由于 fetch 功能尚未执行。

  2. 您发送了一个参数 { json: true },该参数尝试获取 JSON 格式的响应。但请求的 URL 以普通文本文档/HTML 文档回复。因此,删除该参数肯定会有所帮助。

    const fs = require('fs');
    const got = require('got');
    
    function fetch(){
        got('https://www.google.com' ).then(response => {
        console.log("Response");
        temp = response.body;
        fs.writeFile('demo3.txt', temp  , { flag: "a"}, function(err){
            if(err){
                return console.log(err);
            }
            });
            }).catch(error => {
            console.log(error);
        });
    };
    
    fetch();  
    

这里 fs.write 将在“got”函数通过返回响应变量完成其执行后执行。在这里,我还删除了参数 { json: true } ,因为响应不是 JSON 格式。


推荐阅读