Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending data through POST request from a node.js server to a node.js server

Tags:

node.js

I'm trying to send data through a POST request from a node.js server to another node.js server. What I do in the "client" node.js is the following:

var options = {     host: 'my.url',     port: 80,     path: '/login',     method: 'POST' };  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(chunk){         console.log("body: " + chunk);     }); });  req.on('error', function(e) {     console.log('problem with request: ' + e.message); });  // write data to request body req.write('data\n'); req.write('data\n'); req.end(); 

This chunk is taken more or less from the node.js website so it should be correct. The only thing I don't see is how to include username and password in the options variable to actually login. This is how I deal with the data in the server node.js (I use express):

app.post('/login', function(req, res){     var user = {};     user.username = req.body.username;     user.password = req.body.password;         ... }); 

How can I add those username and password fields to the options variable to have it logged in?

Thanks

like image 376
Masiar Avatar asked Mar 19 '12 10:03

Masiar


People also ask

How do I transfer data from one server to another in node JS?

In function getMeetingRequestData we will send http request by using http module and return the data to the callback. By this way we can send data to another server in node. js.

How do you send a POST 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).

Which method is used to send the data from node js server to client?

Methods to send response from server to client are: Using send() function. Using json() function.


2 Answers

Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?) as the request body.

This requires Content-Type and Content-Length headers, so the receiving server knows how to interpret the incoming data. (*)

var querystring = require('querystring'); var http = require('http');  var data = querystring.stringify({       username: yourUsernameValue,       password: yourPasswordValue     });  var options = {     host: 'my.url',     port: 80,     path: '/login',     method: 'POST',     headers: {         'Content-Type': 'application/x-www-form-urlencoded',         'Content-Length': Buffer.byteLength(data)     } };  var req = http.request(options, function(res) {     res.setEncoding('utf8');     res.on('data', function (chunk) {         console.log("body: " + chunk);     }); });  req.write(data); req.end(); 

(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded for the traditional format that a standard HTML form would use.

It's easy to send JSON (application/json) in exactly the same manner; just JSON.stringify() the data beforehand.

URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.

The bottom line is: The server must be able to interpret the content type in question. It could be text/plain or anything else; there is no need to convert data if the receiving server understands it as it is.

Add a charset parameter (e.g. application/json; charset=Windows-1252) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.

like image 121
Tomalak Avatar answered Sep 20 '22 23:09

Tomalak


You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.

Just do the following for executing a POST request:

var requestify = require('requestify');  requestify.post('http://example.com', {     hello: 'world' }) .then(function(response) {     // Get the response body (JSON parsed or jQuery object for XMLs)     response.getBody(); }); 
like image 24
ranm8 Avatar answered Sep 17 '22 23:09

ranm8