如何写curl' PUT'在节点中请求'请求'模

时间:2017-01-25 05:04:36

标签: node.js curl autodesk-forge autodesk-model-derivative

我有这个卷曲请求。

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请求模块的节点中编写此代码。 我尝试了下面的请求'和' fs'。 我回来了#34;请求中未提供令牌"。

    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);
                }
            })
    }

1 个答案:

答案 0 :(得分:2)

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

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

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>"
        }
    */
}))