【问题标题】:Using file content as object data使用文件内容作为对象数据
【发布时间】:2022-01-17 16:20:23
【问题描述】:

我正在尝试使用 .json 文件中的 formData 发送 http 请求,但无法将数据正确添加到 options 对象中。

{"name":"charlie","age":"20"}

下面是我现在要做的事情。

fs.readFile(__dirname + directory, (error, data) => { 
  if(error) {throw error;}
  data = JSON.stringify(JSON.parse(data))

  var options = {
    'method': 'GET',
    'url': 'https://google.com',
    formData: data
  };

  .............

});

这不符合我的预期,因为它将data 视为在内容周围放置撇号的字符串。我尝试使用Object.assign,但我再次遇到了我的data 被视为字符串的问题。
任何帮助将不胜感激,在过去的 2 个小时里,我一直在尝试对此进行研究,但运气不佳。
如果您对 request.js 以外的更好的系统或软件包有任何建议,我很乐意听到。
再次感谢您抽出宝贵时间。

【问题讨论】:

    标签: javascript node.js object


    【解决方案1】:

    问题是.... formData: 需要一个以 Formdata 作为其数据类型的变量: 这应该工作:)

    const fs = require('fs')
    fs.readFile("C:/tes/test.json", (error, data) => { 
        if(error) {throw error;}
        let fdata = FormData()
        console.log(data)
        data = JSON.parse(data)
        console.log(data)
        console.log(data.name)
    
        fdata.append("name", data.name)
        fdata.append("age", data.age)
    
        var options = {
          'method': 'GET',
          'url': 'https://google.com',
          formData: fdata
        };
      });
    

    【讨论】:

    猜你喜欢
    • 2019-06-16
    • 1970-01-01
    • 2017-11-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 2011-07-09
    • 1970-01-01
    相关资源
    最近更新 更多