gpt4 book ai didi

node.js - 如何使用 'PUT'模块在 Node 中编写curl 'request'请求

转载 作者:太空宇宙 更新时间:2023-11-03 23:27:48 24 4
gpt4 key购买 nike

我有这个 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 请求模块在 Node 中编写此内容。我用“request”和“fs”尝试了以下操作。我得到回复“请求中未提供 token ”。

    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 构造的相同请求进行比较。这是最终的工作版本:

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

关于node.js - 如何使用 'PUT'模块在 Node 中编写curl 'request'请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41843761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com