Skip to content

Commit 46914a1

Browse files
committed
feat: 新建中间件 SSE header
1 parent 67ba332 commit 46914a1

File tree

4 files changed

+19
-8
lines changed

4 files changed

+19
-8
lines changed

app.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ const json = require('koa-json');
44
const onerror = require('koa-onerror');
55
const bodyparser = require('koa-bodyparser');
66
const logger = require('koa-logger');
7+
const sseHeader = require('./middlewares/sseHeader');
78
const cors = require('./middlewares/cors');
89
const db = require('./libs/db');
910

@@ -37,8 +38,12 @@ app.use(async (ctx, next) => {
3738
// set CORS header
3839
app.use(cors());
3940

41+
// set sse headers
42+
app.use(sseHeader());
43+
4044
// routes
4145
app.use(routeClient.routes(), routeClient.allowedMethods());
4246
app.use(routeServer.routes(), routeServer.allowedMethods());
4347

48+
4449
module.exports = app;

middlewares/sseHeader.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
module.exports = () => async (ctx, next) => {
2+
if (/^\/alive/.test(ctx.path)) {
3+
// otherwise node will automatically close this connection in 10 minutes.
4+
ctx.req.setTimeout(1000 * 60 * 10);
5+
ctx.type = 'text/event-stream; charset=utf-8';
6+
ctx.set('Cache-Control', 'no-cache');
7+
ctx.set('Connection', 'keep-alive');
8+
ctx.set('X-Accel-Buffering', 'no');
9+
}
10+
await next();
11+
};

public/index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
Hello World!
1111
</body>
1212
<script>
13-
const url = '/test';
13+
const url = '/alive/test';
1414
var source = new EventSource(url);
1515
source.addEventListener('open', function (event) {
1616
console.log('open');

routes/client.js

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,12 @@
55
const router = require('koa-router')();
66
const sse = require('../libs/sse');
77

8+
router.prefix('/alive');
9+
810
router
911
.get('/test', async (ctx) => {
1012
// otherwise node will automatically close this connection in 10 minutes.
11-
ctx.req.setTimeout(1000 * 60 * 10);
12-
ctx.type = 'text/event-stream; charset=utf-8';
13-
ctx.set('Cache-Control', 'no-cache');
14-
ctx.set('Connection', 'keep-alive');
15-
ctx.set('X-Accel-Buffering', 'no');
16-
1713
const body = ctx.body = new sse();
18-
1914
const ssid = ctx.cookies.get('ssid');
2015
if (ssid) {
2116
global.table[ssid] = body;

0 commit comments

Comments
 (0)