简体   繁体   中英

how to send HTTP request to submit form in node.js to another website?

I want to submit a form of another sites & want get response. But cant understand how to do this. Can anyone please help me ?

My target site : http://xyz.php

My code :

var http = require('http');
var options = {
  host: 'xyz.com',
  path: '/xyz.php?textSearch=234567'
};

callback = function(response) {
  var str = '';
  response.on('data', function (chunk) {
    str += chunk;
  });
  response.on('end', function () {
    console.log(str);
  });
}

http.request(options, callback).end();

You should use POST request, because form tag contain method attribute

 <form id="frmThis" name="frmThis" method="post" action="">

Try this code:

var querystring = require('querystring');
var http = require('http');

var post_data = querystring.stringify({
    txtSearch: "17051017387"
})

var options = {
    host: 'nbr.gov.bd',
    path: '/getbinfield.php',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': post_data.length
    }
};

callback = function(response) {
    console.log(arguments);
    var str = '';
    response.on('data', function (chunk) {
        str += chunk;
    });
    response.on('end', function () {
        console.log(str);
    });
}

var req = http.request(options, callback)
req.write(post_data)
req.end()

Using the request module:

var request = require('request')
request.post('http://nbr.gov.bd/getbinfield.php', {
  form: {
    txtSearch: '...search for something',
    bthSubmit: 'Search'
  }
}, function (err, res, body) {
  console.log(body)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM