gpt4 book ai didi

使用 express-ws 的 "app.ws" typescript 错误

转载 作者:行者123 更新时间:2023-12-05 01:41:48 25 4
gpt4 key购买 nike

在我的小项目中,我想构建一个可以使用 Raspberry Pi Zero 从任何网络浏览器访问的 BabyCam。为此,我想使用 express-is 打开一个网络套接字,以将视频流式传输到多个客户端。我将大部分与视频相关的代码基于 raspivid-stream module .但是,当尝试访问 Web 套接字时,我收到 app.ws(... 的类型错误,指出 Property 'ws' does not exist on type 'Application' . 当然,我导入了 express 和 express-ws 的类型。

我不太确定问题出在哪里,因为 JavaScript 中的相同调用似乎工作正常。这是代码 - 我很高兴能得到任何帮助!

import express from 'express';
import { Request, Response } from 'express';
import fs from 'fs';
import https from 'https';
import http from 'http';
import raspividStream from 'raspivid-stream';
import expressWs from 'express-ws';


const server: express.Application = express();

const httpPort: number = 8080;
const httpsPort: number = 8443;

const sslCredentials = {
key: fs.readFileSync('../ssl/localhost.key', 'utf8'),
cert: fs.readFileSync('../ssl/localhost.cert', 'utf8')
};

// CREATE SERVER

const httpServer = http.createServer(server);
const httpsServer = https.createServer(sslCredentials, server);

expressWs(server, httpsServer);

// ROUTES

server.get('*', (req: Request, res:Response) => {
if (!req.secure) {
return res.redirect(`https://${req.hostname}:${httpsPort}${req.originalUrl}`);
}
res.sendFile(__dirname + '/client/index.html');
});

// WEBSOCKET

server.ws('/video-stream', (ws) => {
console.log('Client connected');


ws.send(JSON.stringify({
action: 'init',
width: '960',
height: '540'
}));

var videoStream = raspividStream({ rotation: 180 });

videoStream.on('data', (data) => {
ws.send(data, { binary: true }, (error) => { if (error) console.error(error); });
});

ws.on('close', () => {
console.log('Client left');
videoStream.removeAllListeners('data');
});
});


// START SERVER

httpServer.listen(httpPort, () => {
console.log(`BabyCam (redirect) listening at http://localhost:${httpPort}/`);
});

httpsServer.listen(httpsPort, () => {
console.log(`BabyCam (SSL) listening at https://localhost:${httpsPort}/`);
});

最佳答案

我看过https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/express-ws/index.d.ts .

这是(我认为)Stramski 的回答的意思:

import * as path from 'path';
import * as express from 'express';
import * as expressWs from 'express-ws';

const SERVER_PORT = 8090;

let appBase = express();
let wsInstance = expressWs(appBase);
let { app } = wsInstance; // let app = wsInstance.app;

// Http Routes
app.use('/assets', express.static(path.join(process.cwd(), 'assets')));

// Ws Routes
app.ws('/echotwice', (ws, req) => {
ws.on('message', msg => {
ws.send(msg + msg);
});
});

app.listen(SERVER_PORT, () => {
console.log(`App listening on port ${SERVER_PORT}!`);
});

关于使用 express-ws 的 "app.ws" typescript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53573895/

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