Node.js:转发MJPEG流到客户端应用程序



我试图在我的Next.js前端向Axis API发出请求后,在我的自定义Node.js服务器中显示Axis摄像机直播流。在发出这个请求之后

const response = await client.fetch(`http://${ip}/axis-cgi/mjpg/video.cgi?resolution=${resolution}&fps=${fps}&compression=${compression}`, {
method: 'GET',
headers: {
'Content-Type': 'multipart/x-mixed-replace; boundary=--myboundary',
},
});

我得到一个状态码为200的响应,响应体中有以下内容:

PassThrough {
_readableState: ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: [Object], tail: [Object], length: 1 },
length: 65351,
pipes: [],
flowing: null,
ended: false,
endEmitted: false,
reading: false,
constructed: true,
sync: false,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
errorEmitted: false,
emitClose: true,
autoDestroy: true,
destroyed: false,
errored: null,
closed: false,
closeEmitted: false,
defaultEncoding: 'utf8',
awaitDrainWriters: null,
multiAwaitDrain: false,
readingMore: false,
dataEmitted: false,
decoder: null,
encoding: null,
[Symbol(kPaused)]: null
},
_events: [Object: null prototype] {
prefinish: [Function: prefinish],
unpipe: [Function: onunpipe],
error: [ [Function: onerror], [Function (anonymous)] ],
close: [Function: bound onceWrapper] { listener: [Function: onclose] },
finish: [Function: bound onceWrapper] { listener: [Function: onfinish] },
drain: [Function: pipeOnDrainFunctionResult]
},
_eventsCount: 6,
_maxListeners: undefined,
_writableState: WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: true,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 65351,
writing: true,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: [Function: nop],
writelen: 65351,
afterWriteTickInfo: null,
buffered: [],
bufferedIndex: 0,
allBuffers: true,
allNoop: true,
pendingcb: 1,
constructed: true,
prefinished: false,
errorEmitted: false,
emitClose: true,
autoDestroy: true,
errored: null,
closed: false,
closeEmitted: false,
[Symbol(kOnFinished)]: []
},
allowHalfOpen: true,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: [Function: bound onwrite]
}

我的问题是如何使用这些数据在前端显示MJPEG ?最初,我将URL传递给img标记,但这种方法在生产环境中不起作用,因为URL不安全。

OK。我从来没有这样做过,但在谷歌上快速搜索后,我认为这是可能的,你想做什么。对于next.js,你可以这样做:

警告:未经测试的代码

为你的MJPEG流创建一个API端点。

从这个问题的答案(使用NodeJS的多部分/混合响应)来看,在处理程序中,你可以将获取响应管道到res对象(假设你的client.fetch函数实现了获取API)。

function handler(req, res) {
const response = await client.fetch(url, options);
response.body.pipeTo(res);
}

在客户端,只需将img标记的src属性设置为API端点的URL。你可以在URL中使用会话cookie或会话哈希来保护API端点,但使用授权头不起作用,因为img标记不能在其请求中设置自定义头。

相关内容

  • 没有找到相关文章

最新更新