NodeJS请求如何发送multipart/form-data POST请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49053193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:43:20  来源:igfitidea点击:

NodeJS Request how to send multipart/form-data POST request

node.jsrequestmultipartform-data

提问by Paul de Koning

I'm trying to send a POST request to an API with an image in the request. I'm doing this with the request module but everything I try it isn't working. My current code:

我正在尝试将 POST 请求发送到请求中带有图像的 API。我正在使用请求模块执行此操作,但是我尝试的所有操作都不起作用。我目前的代码:

const options = {
    method: "POST",
    url: "https://api.LINK.com/file",
    port: 443,
    headers: {
        "Authorization": "Basic " + auth,
        "Content-Type": "multipart/form-data"
    },
    form : {
        "image" : fs.readFileSync("./images/scr1.png")
    }
};

request(options, function (err, res, body) {
    if(err) console.log(err);
    console.log(body);
});

But request uses Content-Type: application/x-www-form-urlencodedfor some reason... How can I fix this?

但是Content-Type: application/x-www-form-urlencoded出于某种原因请求使用......我该如何解决这个问题?

回答by Ivan Vasiljevic

As explained in documentationform multipart/form-datarequest is using form-datalibrary. So you need to supply formDataoption instead of formoption.

正如文档表单中所解释的,multipart/form-data请求正在使用form-data库。所以你需要提供formData选项而不是form选项。

const options = {
    method: "POST",
    url: "https://api.LINK.com/file",
    port: 443,
    headers: {
        "Authorization": "Basic " + auth,
        "Content-Type": "multipart/form-data"
    },
    formData : {
        "image" : fs.createReadStream("./images/scr1.png")
    }
};

request(options, function (err, res, body) {
    if(err) console.log(err);
    console.log(body);
});