发送POST请求并通过Node.js获取数据
我一直在努力发送POST请求和使用Node.js获取数据
我一直在这样试用
var querystring = require('querystring'); var http = require('http'); var postData = querystring.stringify({ }); var options = { hostname: 'www.google.com', port: 80, path: '/', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': postData.length } }; 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); }); res.on('end', function() { console.log('No more data in response.') }) }); req.on('error', function(e) { console.log('problem with request: ' + e.message); }); req.write(postData); req.end();
但是我卡在postData
,不知道会做什么。 请帮帮我。 如何在Web上填写表单,然后请求POST方法(在这种情况下,单击Google上的searchbutton),然后获取数据响应?
Googlesearch在search时不使用POST方法,它使用GET方法。 你必须改变方法到GET,删除postData和embedded数据发送到URL本身。
var options = { hostname: 'www.google.com', port: 80, path: '/#q'+search_key, //search_key is term to be searched method: 'GET' };
或者你也可以这样使用
http.get("http://www.google.com/#q="+search_key, function(res) { console.log("Got response: " + res.statusCode); }).on('error', function(e) { console.log("Got error: " + e.message); });