【问题标题】:Fs.writeFile writes [Object, Object] instead of writing the actual responseFs.writeFile 写入 [Object, Object] 而不是写入实际响应
【发布时间】:2021-01-01 01:46:06
【问题描述】:

我正在尝试将此 API 调用的响应写入 message.txt,但我只得到 [Object Object] 而 console.log 向我显示响应的确切内容。我哪里错了?谢谢。

axios({
    "method": "GET",
    "url": "https://twelvedata.p.rapidapi.com/bbands",
    "headers": {
      "content-type": "application/octet-stream",
      "x-rapidapi-host": "twelvedata.p.rapidapi.com",
      "x-rapidapi-key": "hidden",
      "useQueryString": true
    },
    "params": {
      "sd": "2",
      "outputsize": "120",
      "series_type": "close",
      "ma_type": "SMA",
      "time_period": "20",
      "symbol": "AAPL",
      "interval": "5min",
      "apikey": "hidden"
    }
  })
  .then((res) => {
    fs.writeFile('message.txt', res, (err) => {
      if(err) {
        console.log('err: ', err);
      }
    })
  })
  .catch((error) => {
    console.log(error)
  })

【问题讨论】:

    标签: node.js api get axios


    【解决方案1】:

    将 [object Object] 写入文件的原因是这是默认 Object.toString() 调用的结果,fs.writeFile 正在使用该调用将对象序列化为字符串。

    获得所需行为的最简单方法是在写入文件之前自己将 Object 转换为字符串。 JSON.stringify 是最直接的方法。

    例如:

    axios({
        "method": "GET",
        "url": "https://twelvedata.p.rapidapi.com/bbands",
        "headers": {
          "content-type": "application/octet-stream",
          "x-rapidapi-host": "twelvedata.p.rapidapi.com",
          "x-rapidapi-key": "hidden",
          "useQueryString": true
        },
        "params": {
          "sd": "2",
          "outputsize": "120",
          "series_type": "close",
          "ma_type": "SMA",
          "time_period": "20",
          "symbol": "AAPL",
          "interval": "5min",
          "apikey": "hidden"
        }
      })
      .then((res) => {
        // Serialize the res object using JSON.stringify
        fs.writeFile('message.txt', JSON.stringify(res.data, null, 4), (err) => {
          if(err) {
            console.log('err: ', err);
          }
        })
      })
      .catch((error) => {
        console.log(error)
      })
    

    【讨论】:

    • 谢谢它有效,但我不确定我是否理解它为什么有效。那是:1-首先 axios 自动将数据从 JSON 解析为 JS,2- Fs.writeFile 获取已解析的 JS 对象并对其执行 Object.toString(),但这样做只会写入 [object, Object] 3- 而如果 Fs.writeFile 对 JSON 数据执行 Object.toString() 它会完整地写入它吗?我做对了吗?
    • 是的,没错,axios会将数据解析成一个对象,虽然响应体本身会在response.data中,所以我们实际上可能想做JSON.stringify(res.data, null , 4) 而不是将整个响应保存到文件中(我们可能不需要很多额外的数据)。 2. 我认为是我们将看到的行为,虽然对于 3,JSON.stringify 调用会将对象转换为字符串,因此 fs.writeFile 可以直接写入文件而无需调用 .toString (因为它是一个字符串已经)。
    • 没问题,很高兴为您提供帮助!
    猜你喜欢
    • 2016-10-17
    • 2014-12-11
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    相关资源
    最近更新 更多