简体   繁体   English

Axios POST 在 Node.js 但不是 Electron

[英]Axios POST working in Node.js but not Electron

So I have a package with a function that uploads a file to Twilio:所以我有一个 package 和一个 function 将文件上传到 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(),
    },
    })

}

This works completely fine in node.js and it gets uploaded with the message "Hello World" in the file.这在 node.js 中完全可以正常工作,并在文件中与消息“Hello World”一起上传。

I'm trying to put this into an electron app so I preload this package in preload.js with nodeIntegration set to true but whenever I try to upload a file I get:我正在尝试将其放入 electron 应用程序中,因此我在 preload.js 中预加载此 package 并将 nodeIntegration 设置为 true 但每当我尝试上传文件时,我都会得到:

Request failed with status code 400

With the error response being:错误响应为:

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

Does preloading a package make it act exactly the same as it does in node.js?预加载 package 是否使其行为与 node.js 中的行为完全相同?

Can u add cotent-type in headers section and check.你可以在标题部分添加 cotent-type 并检查。

"content-type": "application/json" “内容类型”:“应用程序/json”

Even though you may try and preload a package with axios hoping it runs in a node environment, requests are done under XHR (browser).即使您可以尝试预加载 package 和 axios 希望它在节点环境中运行,但请求是在 XHR(浏览器)下完成的。

To fix this you must specify the adapter to be HTTP by adding adapter: require('axios/lib/adapters/http')要解决此问题,您必须通过添加adapter: require('axios/lib/adapters/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'),
    })
}

How did you solve the issue?你是如何解决这个问题的? I'm having a similar issue where my Axios POST works fine on node, but fails on Electron due to Content Security Policy directive , no matter how I set the connect-src directive.我有一个类似的问题,我的 Axios POST 在节点上工作正常,但由于Content Security Policy directive而在 Electron 上失败,无论我如何设置 connect-src 指令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM