7 Star 0 Fork 0

常鹏/Express后端

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
app.js 6.81 KB
一键复制 编辑 原始数据 按行查看 历史
常鹏 提交于 2023-06-01 15:01 . 1
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var multiparty = require('multiparty'); //上传图片模块
var cors = require('cors');
var expressJWT = require("express-jwt")
var websocketServe = require("./websocketconfig")
// 启动websocket服务
// websocketServe()
// var redis = require("./redis/RedisHelper")
// redis.SetString("code","336548")
// redis.GetString("code").then((res)=>{
// console.log(res)
// })
// 直播模块
const NodeMediaServer = require('node-media-server');
const config = {
rtmp: {
port: 1935, // rtmp端口号
chunk_size: 60000, // 单个拆分媒体流的包的大小
gop_cache: true,
ping: 30,
ping_timeout: 60
},
http: {
port: 8000, // http端口号
allow_origin: '*' // 允许跨域
}
};
var nms = new NodeMediaServer(config)
// nms.run();
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var cpRouter = require('./routes/cp');
var twkRouter = require('./routes/twk');
var gzjRouter = require('./routes/gzj');
var jyhRouter = require('./routes/jyh');
var tyhRouter = require('./routes/tyh');
var ztRouter = require('./routes/zt');
var zjbRouter = require('./routes/zjb');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/cp', cpRouter);
app.use('/twk', twkRouter);
app.use('/gzj', gzjRouter);
app.use('/jyh', jyhRouter);
app.use('/tyh', tyhRouter);
app.use('/zt', ztRouter);
app.use('/zjb', zjbRouter);
// 配置token认证
// app.use(expressJWT({
// secret: "tangweike",
// algorithms: ['HS256']
// }).unless({
// path: [
// "/twk/login",
// { url: /^\/upload/, methods: ["GET"] }
// ]
// }))
//配置上传图片虚拟路由和上传目录
app.use('/upload', express.static('upload'))
//配置图片接收返回路径
app.post('/imgs', (req, res) => {
let imgDir = new multiparty.Form()
imgDir.uploadDir = 'upload'
imgDir.parse(req, async (err, data, img) => {
// console.log(img.flie[0].path, '***');
let image = img.file[0].path.split('upload\\')[1]
console.log(`http://127.0.0.1:3366/upload/${image}`, '8888888888');
res.send(`http://127.0.0.1:3366/upload/${image}`)
})
})
const WsList = [];
const WsIdList = [];
const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8080 });
wss.on("connection", function connection(ws, req) {
ws.send("连接成功")
id = req.url.split("=")[1]
ws["id"] = id
if (WsIdList.indexOf(id) == -1) {
WsIdList.push(id) /
WsList.push(ws)
console.log(WsIdList, '用户登录ID');
// console.log(WsList, 'WS存储ID')
}
// 监听客户端发过来的消息
ws.on("message", function message(msg, isBinary) {
console.log('客户端数据:::', JSON.parse(msg.toString()));
let data = JSON.parse(msg.toString())
let toId = data.id
let type = data.type
WsList.forEach(item => {
console.log(item.id, toId, '66666666666666');
if (item.id == toId) {
console.log(item.id, toId, '4444444444444');
if (type == 'receive') {
item.send(data.value)
}
}
})
})
})
// const WsList = []
// const WsIdList = []
// const { WebSocketServer } = require('ws');
// const server = new WebSocketServer({ port: 8000 });
// server.on('connection', handleConnection)
// function handleConnection(ws, req) {
// console.log('--- Server is connected 服务器已连接 ---')
// ws.on('close', handleClose)
// ws.on('error', handleError)
// ws.on('message', handleMessage)
// function handleClose() {
// console.log('--- Server is closed 服务器已关闭 ---');
// // this.send()
// ws.send(JSON.stringify({
// mode: 'MESSAGE', //模式
// msg: '--- Server is closed 服务器已关闭 ---'
// }))
// }
// function handleError(e) {
// console.log('--- Server occured error 服务器发生错误 ---', e);
// }
// /*
// {
// mode:'MESSAGE' or 'HEART_BEAT
// msg:string
// }
// */
// id = req.url.split('=')[1]
// ws["id"] = id
// if (WsIdList.indexOf(id) == -1) {
// WsIdList.push(id)
// WsList.push(ws)
// // console.log(WsList,'socket对象');
// console.log(WsIdList, '用户登录ID');
// }
// function handleMessage(data) {
// console.log('客户端数据:::', JSON.parse(data.toString()));
// const { mode, value,id,type,baseimg } = JSON.parse(data.toString())
// let text = value
// let bimg = baseimg
// let toId = id
// let lettype = type
// switch (mode) {
// case 'MESSAGE':
// console.log('--- User message 用户消息 ---');
// // ws.send(JSON.stringify(JSON.parse(data)))
// WsList.forEach(item=>{
// if(item.id == toId){
// if(lettype == 'receive'){
// console.log('发送执行了');
// if(text == ''){
// item.send(JSON.stringify({bimg,mode:'MESSAGE'}))
// }else{
// item.send(JSON.stringify({text,mode:'MESSAGE'}))
// }
// }
// }
// })
// break
// case 'HEART_BEAT':
// console.log('--- HeartBeat message 心跳机制消息 ---');
// ws.send(JSON.stringify(JSON.parse(data.toString())))
// break
// default:
// break
// }
// }
// }
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
// 解决访问静态文件时候出现跨域的问题
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header(
'Access-Control-Allow-Headers',
'Authorization,X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method'
)
res.header(
'Access-Control-Allow-Methods',
'GET, POST, OPTIONS, PATCH, PUT, DELETE'
)
res.header('Allow', 'GET, POST, PATCH, OPTIONS, PUT, DELETE')
next()
})
// 支持访问mergedUploadFile目录下的静态文件,为他们配置虚拟路径
app.use('/mergedUploadFile', express.static(path.join(__dirname, './public/mergedUploadFile')))
app.use('/video', express.static(path.join(__dirname, './public/video')))
module.exports = app;
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/ChinaCP99/express-backend.git
git@gitee.com:ChinaCP99/express-backend.git
ChinaCP99
express-backend
Express后端
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385