Node.js 请求。获取管道以请求在箱子上张贴
我正在尝试使用获取一个文件(源)和.pipe到一个目标。这种方法在其他云存储(如Dropbox)上运行良好,但Box需要多部分/表单数据上传,因此在请求错误时失败。由于一些要求,我不能使用,我更喜欢这种管道方法 我可能错过了一些时间,因为有一个错误输出:Node.js 请求。获取管道以请求在箱子上张贴,node.js,request,box,Node.js,Request,Box,我正在尝试使用获取一个文件(源)和.pipe到一个目标。这种方法在其他云存储(如Dropbox)上运行良好,但Box需要多部分/表单数据上传,因此在请求错误时失败。由于一些要求,我不能使用,我更喜欢这种管道方法 我可能错过了一些时间,因为有一个错误输出: stream.js:74 throw er; // Unhandled stream error in pipe. ^ Error: write after end at ClientRequest.Outgo
stream.js:74
throw er; // Unhandled stream error in pipe.
^
Error: write after end
at ClientRequest.OutgoingMessage.write (_http_outgoing.js:439:15)
at Request.write (/node_modules/request/request.js:1514:27)
at Request.ondata (stream.js:31:26)
at emitOne (events.js:96:13)
尝试使用,但没有成功,只是更改了错误,而且内容长度也不正确
这是我的源代码
var source = {
url: SOURCE_DOWNLOAD_URL,
method: "GET",
headers: {
'Authorization': 'Bearer ' + SOURCE_TOKEN
},
encoding: null
};
var destination = {
url: 'https://upload.box.com/api/2.0/files/content',
method: 'POST',
headers: {
'Authorization': 'Bearer ' + BOX_TOKEN
},
formData: JSON.stringify({
attributes: {
name: 'somename.txt',
parent: {
id: 1234
}
}
}),
encoding: null
};
request(source).pipe(request(destination)
.on('response', function (resDestination) {
// expecting 201, but returns 400
console.log(destination.method + ' ' + destination.url + ': ' + resDestination.statusCode + ' > ' + resDestination.statusMessage);
}));
尝试创建一个中间流,在向目的地发出请求之前收集所有数据
const Readable = require('stream').Readable
// Create a new Readable instance to write the original request data to
let sourceResponseStream = new Readable()
// no-op function to prevent _read() is not implemented error
sourceResponseStream._read = () => {}
let sourceReq = request(source)
// As we get chunks push them into our new Readable stream
sourceReq.on('data', chunk => {
sourceResponseStream.push(chunk)
})
// Listen for the end of the readable data from the request
sourceReq.on('end', () => {
// mark as no more data to read
sourceResponseStream.push(null)
// Make the request to the destination
let destReq = request(destination, (err, res, body) => {
if (err) {
// handle err
console.log(err)
} else {
console.log(`${destination.method} ${destination.url}: ${res.statusCode} > ${res.statusMessage}`)
}
})
// Pipe our response readable containing our source request data
sourceResponseStream.pipe(destReq)
})
如果这不起作用,您可能需要将
sourceResponseStream
作为formData
对象的属性添加。此外,您可能需要删除formData.attributes
对象周围的JSON.stringify()
。不确定这是否会影响请求的处理方式。仍然是相同的“结束后写入”错误,然后是400>错误Request@AugustoGoncalves更新了我的答案,看看是否有帮助。尝试了所有建议,遗憾的是仍然得到“出站请求启动后,您无法通过管道连接到此流”错误我猜,由于这是一个多部分/表单数据,请求首先发送数据,然后启动文件管道流,导致此问题(与我所遇到的类似,但用不同的词)@AugustoGoncalves此代码发出第一个请求,将所有响应块推送到一个新的可读流中,然后一旦请求完成,生成第二个请求,并通过管道传输新的可读内容,其中包含第一个请求对第二个请求的响应。