简体   繁体   English

发送POST请求并使用Node.js获取数据

[英]Send POST request and fetch data with Node.js

I've been struggling with sending a POST request and fetching data back using Node.js 我一直在努力发送POST请求并使用Node.js取回数据

I've been trialing like this 我一直在这样试

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

But I'm stuck in postData and don't know what would do. 但是我被困在postData ,不知道会怎么做。 Please help me. 请帮我。 How can I fill a form in a web, then request POST method (in this case, click Search button on Google), and then fetch data responded? 如何在网上填写表格,然后请求POST方法(在这种情况下,请单击Google上的“搜索”按钮),然后获取响应的数据?

Google search doesn't use POST method while searching, it uses GET method. Google搜索在搜索时不使用POST方法,而是使用GET方法。 You'll have to change method to GET, remove postData and embed data to be sent in url itself. 您必须将方法更改为GET,删除postData并嵌入要在url本身中发送的数据。

var options = {
    hostname: 'www.google.com',
    port: 80,
    path: '/#q'+search_key, //search_key is term to be searched
    method: 'GET'
};

Or you can use like this also 或者你也可以这样使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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