如何发送HTTP请求以将node.js中的表单提交到另一个网站?

时间:2015-10-24 16:43:29

标签: javascript node.js http request

我想提交另一个网站的表格&想得到回应。但是无法理解如何做到这一点。谁能帮帮我吗 ?

我的目标网站:http://xyz.php

我的代码:

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();

2 个答案:

答案 0 :(得分:1)

您应该使用POST请求,因为表单标记包含方法属性

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

试试这段代码:

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()

答案 1 :(得分:0)

使用request模块:

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)
})