如何使用node发送http request 带文件带参数请求
发布于 8 年前 作者 LiuWenLibra 8406 次浏览 来自 问答

在使用’Content-Type’:‘application/x-www-form-urlencoded’,‘Content-Length’:params.length时可以接收到参数 但要上传文件需要’Content-Type’:‘multipart/form-data;’,‘Connection’:‘keep-alive’。这样参数就接收不到了 此外文件要怎样才能写进请求中让后台可以接收到,求大神帮帮忙啊

var fs = require('fs');
    var http = require('http');
    var querystring = require('querystring');
    var params = JSON.stringify({
        name : '张三'
      });

    var options = {
      host: '127.0.0.1'
      port: 80,
      path: '/abc',
      method: 'post',
      headers: {
	     //使用这个可以接收参数
        //'Content-Type':'application/x-www-form-urlencoded',
        //'Content-Length':params.length,
		//使用这个无法接收参数
        'Content-Type':'multipart/form-data;',
        'Connection':'keep-alive'
      }};

    //使用http 发送
    var req = http.request(options, function(res) {
      console.log('STATUS: ' + res.statusCode);
      console.log('HEADERS: ' + JSON.stringify(res.headers));


      //设置字符编码
      res.setEncoding('utf8');

      //返回数据流
      var _data="";

      //数据
      res.on('data', function (chunk) {
        _data+=chunk;
        console.log('BODY: ' + chunk);
      });

      // 结束回调
      res.on('end', function(){
        console.log("REBOAK:",_data)
      });

      //错误回调
      req.on('error', function(e) {
        console.log('problem with request: ' + e.message);
      });

    });

    req.write(params + "\n");
    req.end();

3 回复

因为 multipart/form-data 需要有 boundary 参数… 可以使用 form-data 构建 https://github.com/form-data/form-data

使用 form.getHeaders() / form.getBoundary() 获取 content-type 相关的 header 信息

回到顶部