Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I pass json data in the request payload of http post request

I wanted to know, how to pass the json request in the payload, for eg: {'name' : 'test', 'value' : 'test'}:

var post_data = {};  var post_options = {   host: this._host,   path: path,   method: 'POST',   headers: {     Cookie: "session=" + session,     'Content-Type': 'application/json',     'Content-Length': post_data.length,   } };  // Set up the request var post_req = http.request(post_options, function (res) {   res.setEncoding('utf8');   res.on('data', function (chunk) {     console.log('========Response========: ' + chunk);   }); });  // post the data post_req.write(post_data); post_req.end(); 
like image 579
Prats Avatar asked Apr 24 '13 09:04

Prats


People also ask

How do I send a POST request with JSON payload?

To send the JSON with payload to the REST API endpoint, you need to enclose the JSON data in the body of the HTTP request and indicate the data type of the request body with the "Content-Type: application/json" request header.

Can you send JSON in a POST request?

POST requestsIn Postman, change the method next to the URL to 'POST', and under the 'Body' tab choose the 'raw' radio button and then 'JSON (application/json)' from the drop down. You can now type in the JSON you want to send along with the POST request. If this is successful, you should see the new data in your 'db.

Can we pass JSON payload GET request?

To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode).


1 Answers

Use the request module

npm install -S request

var request = require('request')  var postData = {   name: 'test',   value: 'test' }  var url = 'https://www.example.com' var options = {   method: 'post',   body: postData,   json: true,   url: url } request(options, function (err, res, body) {   if (err) {     console.error('error posting json: ', err)     throw err   }   var headers = res.headers   var statusCode = res.statusCode   console.log('headers: ', headers)   console.log('statusCode: ', statusCode)   console.log('body: ', body) }) 
like image 179
Noah Avatar answered Sep 19 '22 04:09

Noah