无法使用busboy在本地服务器上发布文件,并且未触发任何事件

时间:2019-02-27 11:29:47

标签: node.js forms server request busboy

我正在尝试使用busboy为端口8000上的本地服务器上传本地png文件。 打开server.js代码,然后启动request.js。问题是除on('finish')外的所有事件都不会触发。似乎png文件的readStream从未传递给busboy,因此它无法触发任何事件。下面是确切的代码。我正在使用Nodejs。

Server.js代码

const fs = require('fs');
var Busboy = require('busboy');
var request=require('request');
http.createServer(function(req, res) {
  if (req.method === 'POST') {

    var busboy = new Busboy({ headers: req.headers });
    req.pipe(busboy);

    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
    });

    busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
             });

    busboy.on('finish', function() {
             });
  } 
else if (req.method === 'GET') {
    res.writeHead(200, { Connection: 'close' });
    res.end('<html><head></head><body>\
               <form method="POST" enctype="multipart/form-data">\
                <input type="text" name="textfield"><br />\
                <input type="file" name="filefield"><br />\
                <input type="submit">\
              </form>\
            </body></html>');
  }
}).listen(8000, function() {
  console.log('Listening for requests');
});

request.js代码

  var create_body = {
textfield: "HEYA",
filename: (__dirname + '/pic1.png'),
filefield: fs.createReadStream(__dirname + '/pic1.png')
}
var ask = {
url: "http://localhost:8000/",
method: "POST",
headers: {
    'content-type': 'multipart/form-data; boundary=----WebKitFormBoundaryzOZ8O14NJBAIsF0V'
},
body: JSON.stringify(create_body),
};

function callback(error, response, body) {
if (error)console.log(error);
request(ask, callback);
}

0 个答案:

没有答案