Skip to content

Commit 27d8166

Browse files
mohammadhonarvaralimd
authored andcommitted
feat(api-server): allow CORS requests to do
1 parent 1dd092f commit 27d8166

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

packages/api-server/src/api-server.ts

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,11 @@ export class NanotronApiServer {
148148
this.httpServer.on('clientError', this.handleClientError_);
149149

150150
if (this.config_.healthRoute) {
151-
this._defineHealthRoute();
151+
this.defineHealthRoute_();
152+
}
153+
154+
if (this.config_.allowAllOrigin === true) {
155+
this.defineCorsRoute_();
152156
}
153157
}
154158

@@ -253,6 +257,10 @@ export class NanotronApiServer {
253257

254258
const connection = new NanotronClientRequest(url, nativeClientRequest, nativeServerResponse, routeOption);
255259

260+
if (this.config_.allowAllOrigin === true) {
261+
connection.serverResponse.headers['access-control-allow-origin'] = '*';
262+
}
263+
256264
if (routeOption === null) {
257265
connection.serverResponse.statusCode = HttpStatusCodes.Error_Client_404_Not_Found;
258266
connection.serverResponse.replyError();
@@ -284,11 +292,12 @@ export class NanotronApiServer {
284292
// TODO: handled open remained connections.
285293
}
286294

287-
protected _defineHealthRoute(): void {
295+
protected defineHealthRoute_(): void {
288296
this.defineRoute({
289297
method: 'GET',
290298
url: '/health',
291299
handler: function () {
300+
this.logger_.logMethod?.('defineHealthRoute_');
292301
const res = this.serverResponse.raw_;
293302
res.statusCode = HttpStatusCodes.Success_200_OK;
294303
res.setHeader('server', 'Alwatr Nanotron');
@@ -297,4 +306,21 @@ export class NanotronApiServer {
297306
},
298307
});
299308
}
309+
310+
protected defineCorsRoute_(): void {
311+
this.defineRoute({
312+
method: 'OPTIONS',
313+
matchType: 'startsWith',
314+
url: '/',
315+
handler: function () {
316+
this.logger_.logMethod?.('defineCorsRoute_');
317+
const res = this.serverResponse.raw_;
318+
res.statusCode = HttpStatusCodes.Success_204_No_Content;
319+
res.setHeader('access-control-allow-origin', '*');
320+
res.setHeader('access-control-allow-methods', '*');
321+
res.setHeader('access-control-allow-headers', '*');
322+
res.end();
323+
},
324+
});
325+
}
300326
}

0 commit comments

Comments
 (0)