Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send a .json file as a HTTP POST using node.js?

I am new to most of these concepts, so I apologize if this question is trivial. I am trying to write a script that makes an HTTP POST request that sends a .json file containing an array of jsons. I am using an npm module found here: https://github.com/request/request and a tutorial that walks you through using the module found here: http://samwize.com/2013/08/31/simple-http-get-slash-post-request-in-node-dot-js/

Here is the code I have so far:

//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)
      }
  })

The data.json file I am trying to send to the local server will contain an array of jsons, formatted like so:

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

So I think I need to make separate POST requests for each array element, but it is not clear to me how to do this.

like image 854
Ryan Swanson Avatar asked May 29 '26 07:05

Ryan Swanson


1 Answers

Here is trivial example. The body needs to be a JSON type, doesnt matter the number of items, as long as the JSON is formatted properly your are good to go!

  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);
});

To include json file, just use require function like normal.

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

like image 160
Remario Avatar answered May 30 '26 20:05

Remario



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!