如何在node.js中发送表单数据

时间:2015-05-12 10:39:21

标签: javascript node.js https multipartform-data form-data

我能够访问服务器但无法发布表单数据。 我应该如何使用https请求发布表单数据? 我正在使用表单数据库表单数据,https请求发布呼叫。 当我运行以下代码时,我能够访问该服务,但该服务会回复说明表单数据未提交。

var https = require('https');
var FormData = require('form-data');
//var querystring = require('querystring');
var fs = require('fs');
var form = new FormData();

connect();

function connect() {
    username = "wr";
    password = "45!"

    var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');
    var options = {
        hostname: 'trans/sun.com',
        port: 443,
        path: '/transfer/upload-v1/file',
        method: 'POST',
        rejectUnauthorized: false,
        headers: {
            'Authorization': auth,
            'Content-Type': 'application/json',
            //'Content-Length': postData.length
        }
    };

    form.append('deviceId', '2612');
    form.append('compressionType', 'Z');
    form.append('file', fs.createReadStream('/Mybugs.txt'));

    var req = https.request(options, function(res) {
        console.log("statusCode: ", res.statusCode);
        //console.log("headers: ", res.headers);
        res.setEncoding('utf8');
        res.on('data', function(d) {
            console.log(d)
        });
    });

    req.write(form + '');
    req.end();

    req.on('error', function(e) {
        console.error(e);
    });
}

1 个答案:

答案 0 :(得分:5)

您永远不会将表单链接到您的请求。请查看form-data documentation

提供的此示例
var http = require('http');

var request = http.request({
  method: 'post',
  host: 'example.org',
  path: '/upload',
  headers: form.getHeaders()
});

form.pipe(request);

request.on('response', function(res) {
  console.log(res.statusCode);
});