Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit 7f2241e

Browse files
author
Abraham
committed
Allowing cors headers to be set for the api so that it can be accessed by ajax calls from Javascript. Cors settings are set from laravel-echo-server.json file. Ran into a situation where I need this and fixed it manually but that's not a long term fix.
1 parent 315d5e9 commit 7f2241e

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

src/api/http-api.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,21 @@ export class HttpApi {
1010
* @param {any} channel
1111
* @param {any} express
1212
*/
13-
constructor(private io, private channel, private express) { }
13+
constructor(private io, private channel, private express, private options) { }
1414

1515
/**
1616
* Initialize the API.
1717
*/
1818
init(): void {
19+
if(this.options.apiOriginAllow.allowCors){
20+
this.express.use( (req, res, next) => {
21+
res.header('Access-Control-Allow-Origin', this.options.apiOriginAllow.allowOrigin);
22+
res.header('Access-Control-Allow-Methods', this.options.apiOriginAllow.allowMethods);
23+
res.header('Access-Control-Allow-Headers', this.options.apiOriginAllow.allowHeaders);
24+
next();
25+
});
26+
}
27+
1928
this.express.get(
2029
'/apps/:appId/status',
2130
(req, res) => this.getStatus(req, res)

src/echo-server.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,13 @@ export class EchoServer {
3434
sslCertPath: '',
3535
sslKeyPath: '',
3636
sslCertChainPath: '',
37-
sslPassphrase: ''
37+
sslPassphrase: '',
38+
apiOriginAllow:{
39+
allowCors : false,
40+
allowOrigin : '',
41+
allowMethods : '',
42+
allowHeaders : ''
43+
}
3844
};
3945

4046
/**
@@ -115,7 +121,7 @@ export class EchoServer {
115121
this.channel = new Channel(io, this.options);
116122
this.redisSub = new RedisSubscriber(this.options);
117123
this.httpSub = new HttpSubscriber(this.server.express, this.options);
118-
this.httpApi = new HttpApi(io, this.channel, this.server.express);
124+
this.httpApi = new HttpApi(io, this.channel, this.server.express, this.options);
119125
this.httpApi.init();
120126

121127
this.onConnect();

0 commit comments

Comments
 (0)