Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post to a request using node.js

I am trying to post some json to a URL. I saw various other questions about this on stackoverflow but none of them seemed to be clear or work. This is how far I got, I modified the example on the api docs:

var http = require('http'); var google = http.createClient(80, 'server'); var request = google.request('POST', '/get_stuff',   {'host': 'sever',  'content-type': 'application/json'}); request.write(JSON.stringify(some_json),encoding='utf8'); //possibly need to escape as well?  request.end(); request.on('response', function (response) {   console.log('STATUS: ' + response.statusCode);   console.log('HEADERS: ' + JSON.stringify(response.headers));   response.setEncoding('utf8');   response.on('data', function (chunk) {     console.log('BODY: ' + chunk);   }); }); 

When I post this to the server I get an error telling me that it's not of the json format or that it's not utf8, which they should be. I tried to pull the request url but it is null. I am just starting with nodejs so please be nice.

like image 522
Mr JSON Avatar asked Dec 22 '10 03:12

Mr JSON


People also ask

How do I POST a request in node JS?

Example code: var request = require('request') var options = { method: 'post', body: postData, // Javascript object json: true, // Use,If you are sending JSON data url: url, headers: { // Specify headers, If any } } request(options, function (err, res, body) { if (err) { console. log('Error :', err) return } console.

How do I send a node js server request?

Server (Node.js)var server = http. createServer(function (request, response) { var queryData = url. parse(request. url, true).

How do I accept a POST request in node?

Paste the following into a file named express-post. js to create a simple web server that responds to a POST request at /sms . Start the server and send a text message to your Twilio phone number. Take a moment to leap to your feet and boogie for receiving your first POST request in Node.


1 Answers

The issue is that you are setting Content-Type in the wrong place. It is part of the request headers, which have their own key in the options object, the first parameter of the request() method. Here's an implementation using ClientRequest() for a one-time transaction (you can keep createClient() if you need to make multiple connections to the same server):

var http = require('http')  var body = JSON.stringify({     foo: "bar" })  var request = new http.ClientRequest({     hostname: "SERVER_NAME",     port: 80,     path: "/get_stuff",     method: "POST",     headers: {         "Content-Type": "application/json",         "Content-Length": Buffer.byteLength(body)     } })  request.end(body) 

The rest of the code in the question is correct (request.on() and below).

like image 122
Ankit Aggarwal Avatar answered Oct 11 '22 12:10

Ankit Aggarwal