Skip to content

Commit

Permalink
feat(api-server): allow CORS requests to do
Browse files Browse the repository at this point in the history
  • Loading branch information
mohammadhonarvar authored and alimd committed Nov 7, 2024
1 parent 1dd092f commit 27d8166
Showing 1 changed file with 28 additions and 2 deletions.
30 changes: 28 additions & 2 deletions packages/api-server/src/api-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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_();
}
}

Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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');
Expand All @@ -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();
},
});
}
}

0 comments on commit 27d8166

Please sign in to comment.