【问题标题】:How do I send a .json file as a HTTP POST using node.js?如何使用 node.js 将 .json 文件作为 HTTP POST 发送?
【发布时间】:2018-01-30 15:36:57
【问题描述】:

我对这些概念中的大多数都不熟悉,所以如果这个问题是微不足道的,我深表歉意。我正在尝试编写一个脚本,该脚本发出一个 HTTP POST 请求,该请求发送一个包含 json 数组的 .json 文件。我正在使用在这里找到的 npm 模块:https://github.com/request/request 以及指导您使用此处找到的模块的教程: http://samwize.com/2013/08/31/simple-http-get-slash-post-request-in-node-dot-js/

这是我目前的代码:

//var fs = require('fs');
var request = require('request');

  // Set the headers
  var headers = {
    'Content-Type': "stuff",
    'x-authorization': "stuff"
  }

  // Configure the request
  var options = {
      url: 'http://localhost:8080/users/add',
      method: 'POST',
      headers: headers,
      form: {
          'username': 'testuser42',
          'firstName': 'test',
          'lastName': 'user42',
          'password': 'testpassword'
      }
  }

  // Start the request
  request(options, function(error, response, body){
      if (!error && response.statusCode == 200) {
          console.log(body)
      }
  })

我试图发送到本地服务器的 data.json 文件将包含一个 json 数组,格式如下:

[
  {
    "username": "testuser1",
    "firstName": "test",
    "lastName": "user1",
    "password": "password1'
  },
  {
    "username": "testuser2",
    "firstName": "test",
    "lastName": "user2",
    "password": "password2'
  }
]

所以我认为我需要为每个数组元素发出单独的 POST 请求,但我不清楚如何做到这一点。

【问题讨论】:

  • 为什么你认为你需要做两个单独的请求?
  • 我认为我的 POST 请求的正文只能包含一个 json 对象。
  • 回答您的问题,整个 data.json 是一个 JSON 文件,因此可以发送整个文件。您唯一应该问自己的是潜在规模
  • 数组的大小是可变的,它不会总是只包含两个对象。
  • 检查我的无聊答案,

标签: javascript node.js http httprequest


【解决方案1】:

这是一个简单的例子。正文需要是 JSON 类型,与项目数量无关,只要 JSON 格式正确即可!

  const obj= {'msg': [
  {
    "username": "testuser1",
    "firstName": "test",
    "lastName": "user1",
    "password": "password1"
  },
  {
    "username": "testuser2",
    "firstName": "test",
    "lastName": "user2",
    "password": "password2"
  }
]};

request.post({
    url: 'your website.com',
    body: obj,
    json: true
  }, function(error, response, body){
  console.log(body);
});

要包含 json 文件,只需像平常一样使用 require 函数。

1:const obj = require('./path_to/data.json');

【讨论】:

  • 这里可以使用promises,而不是回调,只想用最简单的例子
  • 另一个不错的选择是 Axios,
  • 但在我的情况下,包含 json 项目的“obj”位于单独的本地文件中。所以我想我要问的是如何将该文件读入我的脚本?
  • 非常感谢!
  • 好吧,如果有帮助,请接受未来 OP 的答案。欢迎您
猜你喜欢
  • 2019-10-29
  • 1970-01-01
  • 1970-01-01
  • 2017-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-21
  • 1970-01-01
相关资源
最近更新 更多