【问题标题】:CURL Command to NodeJS - PUT Request OctetStream节点 JS 的 CURL 命令 - PUT 请求八位字节流
【发布时间】:2022-01-04 15:52:45
【问题描述】:

我需要使用 fetch、request 或 axios 网络库将这个 curl 命令转换为 nodejs 请求

请求需要PUT将文件数据发送到URL

curl -v -H "Content-Type:application/octet-stream" --upload-file C:/Users/deanv/Pictures/test3.mp4 "https://www.example.com/file/upload"

我尝试使用CurlConverter 将我的 curl 命令转换为节点代码,但这不起作用,因为我无法添加文件数据。

var fetch = require('node-fetch');

fetch('https://www.example.com/file/upload', {
    method: 'PUT',
    headers: {
        'Content-Type': 'application/octet-stream'
    }
});

感谢所有帮助。提前致谢。

【问题讨论】:

    标签: javascript node.js curl networking


    【解决方案1】:

    试试这个:

    // setup modules
    const fetch = require('node-fetch');
    const FormData = require('form-data');
    const fs = require('fs');
    const path = require('path');
    
    // setup paths
    const pathToFile = 'C:/Users/deanv/Pictures/test3.mp4';
    const uploadUrl = 'https://www.example.com/file/upload';
    
    // create form, 'content-type' header will be multipart/form-data
    const form = new FormData();
    
    // read the file as stream
    const fileStream = fs.createReadStream(path.resolve(pathToFile));
    
    // add the file to the form
    form.append('my_file', fileStream);
    
    fetch(uploadUrl, {
            method: 'PUT',
            body: form
        }).then((res) => {
            console.log('done: ', res.status);
            return res.text();
        })
        .then((res) => {
            console.log('raw response: ', res);
        })
        .catch(err => {
            console.log('err', err);
        });
    

    【讨论】:

    • 我得到一个done 400 作为记录到控制台的状态码
    • 这是“400 Bad Request”的缩写。服务器抱怨某事.. 我更新了代码以记录服务器响应
    • 我只是使用 curl 并使用 exec 来调用它。谢谢你的帮助。当 curl 做得很好时,我只是放弃了使用 node js
    猜你喜欢
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 2018-05-04
    相关资源
    最近更新 更多