【问题标题】:Axios POST working in Node.js but not ElectronAxios POST 在 Node.js 中工作,但不适用于 Electron
【发布时间】:2021-06-11 13:16:31
【问题描述】:

所以我有一个包,其中包含将文件上传到 Twilio 的功能:

const FD = require('form-data');
const axios = require('axios');

   async function createFunctionResource(serviceUid, functionUid, client){

    let collect_file = "Hello World"

    let url = `https://serverless-upload.twilio.com/v1/Services/${serviceUid}/Functions/${functionUid}/Versions`

    let form = new FD();
    collect_file = "test"

    form.append("Path", "collect");
    form.append("Visibility", "public");
    form.append("Content", collect_file, "collect.js");
    form.append("contentType", "application/javascript");

    await axios.post(url, form,  {
    headers: {
        Authorization: 'Basic ' + Buffer.from(`${client.accountSid}:${client.password}`).toString('base64'),
        ...form.getHeaders(),
    },
    })

}

这在 node.js 中完全可以正常工作,它会在文件中与消息“Hello World”一起上传。

我正在尝试将其放入电子应用程序中,因此我在 preload.js 中预加载此包,并将 nodeIntegration 设置为 true,但每当我尝试上传文件时,我都会得到:

Request failed with status code 400

错误响应为:

{"message":"No file attached to request","code":70002,"user_error":true,"http_status_code":400,"params":{}}

预加载一个包是否使其行为与在 node.js 中完全相同?

【问题讨论】:

    标签: javascript node.js electron twilio node-modules


    【解决方案1】:

    你可以在标题部分添加 cotent-type 并检查。

    “内容类型”:“应用程序/json”

    【讨论】:

      【解决方案2】:

      尽管您可以尝试使用 axios 预加载一个包,希望它在节点环境中运行,但请求是在 XHR(浏览器)下完成的。

      要解决此问题,您必须通过添加 adapter: require('axios/lib/adapters/http') 将适配器指定为 HTTP

          await axios.post(url, form,  {
          headers: {
              Authorization: 'Basic ' + Buffer.from(`${client.accountSid}:${client.password}`).toString('base64'),
              ...form.getHeaders(),
          },
          adapter: require('axios/lib/adapters/http'),
          })
      }
      

      【讨论】:

        猜你喜欢
        • 2021-09-08
        • 2020-03-16
        • 1970-01-01
        • 2018-06-22
        • 2021-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多