如何使用 'request' 模块在节点中编写 curl 'PUT' 请求

How to write curl 'PUT' request in node with 'request' module

我有这个 curl 请求。

curl -v "https://developer.api.autodesk.com/oss/v2/buckets/:bucketName/objects/" 
-X "PUT" -H "Authorization: Bearer tokenGoesHere" 
-H "Content-Type: application/octet-stream" -T "forupload.rvt"

如何使用 npm 请求模块在节点中编写此代码。 我用 'request' 和 'fs' 尝试了以下操作。 我回来了 "Token is not provided in the request".

    function uploadFile(bucketData){
        var uri = 'https://developer.api.autodesk.com/oss/v2/buckets/' + bucketData['bucketKey'] + '/objects/'
        var authorizationHeader = ' Bearer ' + bucketData['token'] // this works in other post/get requests
        var contentTypeHeader = 'application/octet-stream'
        var streamTarget = 'C:\Users\architech\Desktop\Forge Node\Test.rvt';
        console.log(uri)
        console.log(authorizationHeader)
        console.log(contentTypeHeader)
        console.log(streamTarget)
// console output:
// https://developer.api.autodesk.com/oss/v2/buckets/bucketpqglrzt/objects/
// Bearer ....token....
// application/octet-stream
// C:\Users\architech\Desktop\Forge Node\Test.rvt

        request.put(
            {
                url: uri,
       //       preambleCRLF: true,
       //       postambleCRLF: true,    
                multipart: 
                [
                    {
                        'Authorization': authorizationHeader,
                        'Content-Type': contentTypeHeader,                   
                         body: fs.createReadStream(streamTarget)
                    },  
                ]         
            },

            function(error, response, body){ 
                if(!error){
                    console.log(body);
                }else{
                    console.log(error);
                }
            })
    }

尝试了几种方法后,虽然我无法重现您的具体问题,但我遇到的问题是二进制附件是否正确加载。因为 createReadStream() 异步运行,所以当添加到 multipartformData 键时,它似乎并不像请求文档所说的那样工作。不确定这是为什么?

我首先使用 http://requestb.in 使其工作 - 将 curl 请求与使用 Node.js 构建的相同请求进行比较。这是最终的工作版本:

var request = require('request')
fs = require('fs')

var options = {
    uri: 'https://developer.api.autodesk.com/oss/v2/buckets/<yourBucket>/objects/<yourFile.ext>',
    headers: {
        'Content-Type': 'application/octet-stream',
        'Authorization': 'Bearer <token>'
    }
}

fs.createReadStream(__dirname + '/<fileName.ext>').pipe(request.put(options, function(err, response, body) {
    console.log(body)
    /*
        {
          "bucketKey" : "< yourBucket>",
          "objectId" : "urn:adsk.objects:os.object:brandontestbucket2/skyscpr1.3ds",
          "objectKey" : "<fileName.ext>",
          "sha1" : "...redacted...",
          "size" : 43791,
          "contentType" : "application/octet-stream",
          "location" : "https://developer.api.autodesk.com/oss/v2/buckets/< yourBucket>/objects/<fileName.ext>"
        }
    */
}))