Javascript 如何在 node.js 中发送表单数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30188392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send form data in node.js
提问by Nikhil Deore
I am able to get to the server but unable to post my form data. How should I post the form data with the https request? I am using form-data library for form-data, and https request for post call. When I run the following code, I am able to reach the service, but the service gives a response saying that the form data is not submitted.
我能够访问服务器,但无法发布我的表单数据。我应该如何使用 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);
});
}
回答by Subert
You never link your form to your request. Check this example provided with the 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);
});

