diff --git a/packages/api-server/src/api-server.ts b/packages/api-server/src/api-server.ts index 7c8a2fe..fc284ff 100644 --- a/packages/api-server/src/api-server.ts +++ b/packages/api-server/src/api-server.ts @@ -148,7 +148,11 @@ export class NanotronApiServer { this.httpServer.on('clientError', this.handleClientError_); if (this.config_.healthRoute) { - this._defineHealthRoute(); + this.defineHealthRoute_(); + } + + if (this.config_.allowAllOrigin === true) { + this.defineCorsRoute_(); } } @@ -253,6 +257,10 @@ export class NanotronApiServer { const connection = new NanotronClientRequest(url, nativeClientRequest, nativeServerResponse, routeOption); + if (this.config_.allowAllOrigin === true) { + connection.serverResponse.headers['access-control-allow-origin'] = '*'; + } + if (routeOption === null) { connection.serverResponse.statusCode = HttpStatusCodes.Error_Client_404_Not_Found; connection.serverResponse.replyError(); @@ -284,11 +292,12 @@ export class NanotronApiServer { // TODO: handled open remained connections. } - protected _defineHealthRoute(): void { + protected defineHealthRoute_(): void { this.defineRoute({ method: 'GET', url: '/health', handler: function () { + this.logger_.logMethod?.('defineHealthRoute_'); const res = this.serverResponse.raw_; res.statusCode = HttpStatusCodes.Success_200_OK; res.setHeader('server', 'Alwatr Nanotron'); @@ -297,4 +306,21 @@ export class NanotronApiServer { }, }); } + + protected defineCorsRoute_(): void { + this.defineRoute({ + method: 'OPTIONS', + matchType: 'startsWith', + url: '/', + handler: function () { + this.logger_.logMethod?.('defineCorsRoute_'); + const res = this.serverResponse.raw_; + res.statusCode = HttpStatusCodes.Success_204_No_Content; + res.setHeader('access-control-allow-origin', '*'); + res.setHeader('access-control-allow-methods', '*'); + res.setHeader('access-control-allow-headers', '*'); + res.end(); + }, + }); + } }