Skip to content

Commit

Permalink
Update api for CORS supporting
Browse files Browse the repository at this point in the history
  • Loading branch information
AndreySkripachev committed Jan 27, 2023
1 parent 2439b57 commit 8b1eab3
Show file tree
Hide file tree
Showing 6 changed files with 112 additions and 22 deletions.
2 changes: 2 additions & 0 deletions api/app/config/server.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const port = 8000;
export const host = '0.0.0.0';
21 changes: 21 additions & 0 deletions api/app/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { createServer, ServerResponse, IncomingMessage } from 'http';

import { host, port } from './config/server.config';
import { provideHeaders } from './providers/headers.provider'

function listener(
req: IncomingMessage,
res: ServerResponse<IncomingMessage>
): void {
req.method === 'GET' ?
provideHeaders(res)
.end(JSON.stringify({ message: 'Hello world!' })) :
provideHeaders(res)
.end(JSON.stringify({ data: 'Post request' }))
}

const server = createServer(listener);

server.listen(port, host, () => {
console.log(`Server listening on ${host}:${port}`);
})
11 changes: 11 additions & 0 deletions api/app/providers/headers.provider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { ServerResponse, IncomingMessage } from 'http';

type Response = ServerResponse<IncomingMessage>;

export function provideHeaders(response: Response): Response {
return response
.setHeader('Access-Control-Allow-Origin', '*')
.setHeader('Date', (new Date(Date.now())).toUTCString())
.setHeader('Server', 'CERN/3.0 libwww/2.17')
.setHeader('Content-Type', 'application/json');
}
95 changes: 74 additions & 21 deletions api/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
"author": "Andrey Skripachev",
"license": "ISC",
"dependencies": {
"@types/cors": "^2.8.13",
"@types/express": "^4.17.16",
"@types/node": "^18.11.18",
"typescript": "^4.9.4"
}
}
2 changes: 1 addition & 1 deletion api/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@
"forceConsistentCasingInFileNames": true,
"rootDir": "app"
},
"include": [ "app/*" ],
"include": [ "app/*", "app/core/models" ],
"exclude": [ "node_modules" ]
}

0 comments on commit 8b1eab3

Please sign in to comment.