简体   繁体   English

nodejs / express:如何用数据过帐到外部表单?

[英]nodejs / express: How to POST to an external form with data?

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? 在使用要发布到表单的数据构造一个字符串之后,如何使用nodejs和expressjs将发布到另一个站点上的外部公共表单?

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. 我找不到一个简单的示例或文档,只能继续寻找如何在自己的应用程序中处理和解析POST-ing到表单。

Node.js makes this very easy and it's in their official documentation. Node.js使这非常容易,并且在其官方文档中。

http://nodejs.org/api/http.html#http_http_request_options_callback 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. https://github.com/mikeal/request/是一个很好的易于使用的工具。

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

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

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