HTTPS模块内置的NodeJS进行多部分/表单数据发布请求

时间:2019-03-11 19:16:45

标签: node.js http https telegram multipart

我需要使用Node的内置HTTPS模块将文件上传到API。我当前对API的请求函数是为“ application / json”请求设计的。由docs给出的文件上传说明为:

使用multipart / form-data发布文件,使用的方式通常是通过浏览器上传文件。照片最大大小为10 MB,其他文件最大为50 MB。

我的问题是我不知道如何发出这样的请求,我可以找到有关如何使用Node的内置HTTP / HTTPS模块进行处理的任何信息。

execute(method, params = {}, callback = (res) => {}) {
    let ret = "";
    let options = {
      protocol: "https:",
      hostname: "api.telegram.org",
      port: 443,
      headers: {"Content-Type": "application/json", "Connection":"keep-alive"}, //"Content-Type":"multipart/form-data"
      path: "/bot"+this.token+"/"+method,
      method: "POST"
    };

    let req = this.https.request(options, (res) => {
      res.setEncoding("utf8");

      //Data Stream
      res.on("data", (chunk) => {
        ret += chunk;
        if (res.statusCode != 200) {
          console.error("Something went wrong while connecting to the Telegram API!\n>Status Code: " + res.statusCode + "\n>URL: " + options.hostname + options.path + "\n>Params: " + JSON.stringify(params) + "\n>Response: " + chunk + "\n");
        }
      });

      res.on("error", (err) => {
        console.error(e);
        return;
      });

      //Executes callback after closing the data stream
      res.on("end", () => {
        try {
          ret = JSON.parse(ret).result;
        } catch (e) {
          console.error("Couldn't parse request results!\n>" + e);
          return;
        } finally {
          try {
            callback(ret, params);
          } catch (callbackE) {
            console.error("Error in callback!\n>" + callbackE);
          }
        }
      });
    });

    //Adds parameters
    req.write(""+JSON.stringify(params));
    req.end();
  }

0 个答案:

没有答案