Using NodeJS to Send JSON Data via HTTP POST Request

Issue with Sending JSON Data via Http Post in NodeJS


const http = require('http');
const fs = require('fs');

var options = {
  hostname: 'www.postcatcher.in',
  port: 80,
  path: '/catchers/5531b7faacde130300002495',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  }
};
var req = http.request(options, function(res) {
  console.log('Status: ' + res.statusCode);
  console.log('Headers: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (body) {
    console.log('Body: ' + body);
    fs.writeFile("/var/www/node/test.txt", body, function(err) {
      if(err) {
        return console.log(err);
      }
      console.log("The file was saved!");
    }); 
  });
});
req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('{"string": result}'); // RESULT HERE IS A JSON
req.end();

Additionally tried:

// request.post(
        //     '',
        //     { form: { key: result } },
        //     function (error, response, body) {
        //         if (!error && response.statusCode == 200) {
        //             console.log(body);
        //         }
        //     }
        // );
        // console.log(result);

Answer №1

result is not being dynamically inserted.

It appears that everything is functioning correctly.

http = require('http');
fs = require('fs');

var options = {
    hostname: 'www.postcatcher.in',
      port: 80,
      path: '/catchers/5531b7faacde130300002495',
      method: 'POST',
      headers: {
              'Content-Type': 'application/json',
          }
        };
var req = http.request(options, function(res) {
  console.log('Status: ' + res.statusCode);
  console.log('Headers: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (body) {
    console.log('Body: ' + body);
    fs.writeFile("test.txt", body, function(err) {
    if(err) {
        return console.log(err);
    }
              console.log("The file was saved!");
    }); 
  });
});
req.on('error', function(e) {
  console.log('issue with request: ' + e.message);
});

result = '{ "hello": "json" }';
req.write('{"string": '+result+'}');

req.end();

output:

$ node 29712051.js 
Status: 201
Headers: {"server":"Cowboy","date":"Sat, 18 Apr 2015 04:23:52 GMT","connection":"keep-alive","x-powered-by":"Express","content-type":"text/plain","content-length":"7","set-cookie":["connect.sid=0eGSTYI2RWf5ZTkpDZ0IumOD.OrcIJ53vFcOiQSdEbWz0ETQ9n50JBnXyZRjrSyFIdwE; path=/; expires=Sat, 18 Apr 2015 08:23:53 GMT; httpOnly"],"x-response-time":"6ms","via":"1.1 vegur"}
Body: Created
The file was saved!
$ cat test.txt
Created

Answer №2

Instead of manually creating a JSON string, you can use JSON.stringify(result) like this:

http = require('http');
fs = require('fs');

var options = {
    hostname: 'www.postcatcher.in',
    port: 80,
    path: '/catchers/5531b7faacde130300002495',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    }
};
var req = http.request(options, function(res) {
    console.log('Status: ' + res.statusCode);
    console.log('Headers: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function (body) {
        console.log('Body: ' + body);
        fs.writeFile("test.txt", body, function(err) {
            if(err) {
                return console.log(err);
           }
            console.log("The file was saved!");
        });
    });
});
req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
});

result = JSON.stringify({ hello: "json" });
req.write('{"string": '+result+'}');

req.end();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering the worth of specific selections in a dropdown menu

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <select name="states" id="states"> <option value="100">Hawaii</option> <option value="107">Texa ...

The express response fails to include the HTML attribute value when adding to the href attribute of an

When using my Nodejs script to send an express response, I encounter a problem. Even though I set the href values of anchor tags in the HTML response, they are not visible on the client side. However, I can see them in the innerHTML of the tag. The issue ...

iFrame initially loads the page and subsequently reloads it continuously in a separate tab

Encountering a strange issue with IE11 regarding a series of links: <a href="page1.html" target="iframe_name">Page #1</a> <a href="page2.html" target="iframe_name">Page #2</a> <a href="page3.html" target="iframe_name">Page #3 ...

What are effective strategies for safeguarding my AngularJS application code, particularly from unauthorized access through the browser's source code?

I am currently working on an AngularJS application. I have encountered a challenge where the end user is able to view the app code from the browser's source code. I am seeking advice on how to address this issue effectively. Is there any recommended ...

Exploring the combination of Holder.js and Rails routes

What's the best way to integrate Holder.js into my Rails application? I'm running into issues where Rails is interpreting the parameters passed to the script as routes and returning 404 errors. Has anyone successfully implemented this before? ...

Developing a Multi-Stage Pop-Up with Jquery

I am interested in creating a custom multi-step modal This particular div has dynamically generated classes $('.modal-content').append('<div class="modal-body step step-' + key + '" data-step="'+key+'"></div> ...

Wordpress causing Jquery to malfunction; PHP function not executing

Looking to incorporate a script into my WordPress function.php file. Here's what I have so far: <?php function add_google_jquery() { if ( !is_admin() ) { wp_deregister_script('jquery'); wp_register_script('jquery', ...

Additional headers are included in the Access-Control-Request-Headers

I have been struggling to include a customized header in my angular js GET request like so: $http({ method : 'GET', url : s, headers : { "partnerId" : 221, "partnerKey" : "heeHBcntCKZwVsQo" } ...

A guide on looping through data in a JSON-serialized System.Data.DataTable with the help of jQuery

Here is an example of the JSON format: [ {"animal":"dog", "sound": "bark"}, {"animal":"cat", "sound": "meow"} ] I am looking to iterate over each record {...} within the brackets [ ], starting with the dog-record and then moving on to the cat- ...

The div element with the id "wrapper" is not functioning properly within the box model

I have defined an ID wrapper in CSS: #wrapper { position: relative; background: yellow; -webkit-box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.2); box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.2); width: 960px; padding: 40px 35px 35px ...

Customizing Axios actions in Vue JS using a variable

I have a form in my Vue component that sends a reservation object to my API for storage. I am exploring the possibility of setting the axios action dynamically based on a variable's value, without duplicating the entire axios function (as both the pos ...

Ensure that children elements are aligned to the bottom by setting the axis of the HTML

Elements positioned within a parent DIV typically flow from top to bottom. Even when using Javascript to add elements to the parent DIV, they maintain this top-to-bottom positioning. I am interested in achieving a bottom-to-top axis alignment within the pa ...

Managing dynamically appearing elements in Ember: Executing a Javascript function on them

I'm currently working on a project in Ember and facing an issue with calling a JavaScript function when new HTML tags are inserted into the DOM after clicking a button. Below is a snippet of my code: <script type="text/x-handlebars" id="doc"&g ...

When the mouse hovers over the slider, the final image jumps into view

After successfully building an image slider that displays 2 partial images and 1 full image on hover, I encountered a bug when setting the last image to its full width by default. This caused a temporary gap in the slider as the other images were hovered o ...

Add items to a separate array only if the material UI checkbox is selected

Exploring the world of React, I decided to create a simple todo app using React JS and Material UI. With separate components for user input (TodoInput.js) and rendering individual todos with checkboxes (TodoCards.js), I aim to display the total number of c ...

Syntax error triggered and caught by ajaxError

I have implemented a client-side ajax error handler using the following code: $(document).ajaxError(processAjaxError); $.getJSON('/data.json'); In the server side, I have defined a function as shown below: def get(self): self.response.he ...

Can you explain the purpose of the statement `var MyConstructor = function MyConstructor()`?

Can you explain the distinction between these two code snippets: var NodestrapGenerator = module.exports = function NodestrapGenerator() { yeoman.generators.Base.apply(this, arguments); // more code here }; and: var NodestrapGenerator = module.expor ...

Issue with Contact Form 7: AJAX submission failure leading to redirection to 404 error page

I've been hard at work building a new website that involves using the Wordpress plugin Contact Form 7 to manage form submissions and ideally show a response through AJAX. However, I'm struggling to get the AJAX functionality to function properly ...

Creating a "Container" component in Vue.js step by step

As a newcomer to Vue, I am facing a challenge in implementing a wrapper component similar to React's 'Wrapper' component. Specifically, I want to create a reusable datagrid component using a 3rd-party some-table component and a pagination co ...

Utilize AJAX to verify the content of a PHP variable within a Wordpress environment

After attempting multiple approaches without success, I am seeking advice from anyone who has experience with this particular issue. I have developed a custom post type that generates Public pages. However, I require certain information to only be accessi ...