How do I do a POST to an external public form on another site using nodejs and expressjs after constructing a string with the data I want to POST to the form?
I can't find a straightforward example or documentation for this, only keep finding how to handle and parse POST-ing to a form within your own app.
Node.js makes this very easy and it's in their official documentation.
http://nodejs.org/api/http.html#http_http_request_options_callback
var options = {
host: 'www.google.com',
port: 80,
path: '/upload',
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();
Since question asks about submitting a form, I thought formatting request body is also a concern. You can encode your form yourself; but also use other libraries for convenience.
https://github.com/mikeal/request/ is a good one that is very easy to use.
I use needle:
var needle = require('needle');
needle.post(fullUrl, {
query : query,
maxRows : maxRows,
format : resultsFormat
}, function(err, response, body)
{
if(!err && response.statusCode == 200)
{
///code here
}
});