Skip to content

Commit 8b1eab3

Browse files
author
AndreySkripachev
committed
Update api for CORS supporting
1 parent 2439b57 commit 8b1eab3

File tree

6 files changed

+112
-22
lines changed

6 files changed

+112
-22
lines changed

api/app/config/server.config.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export const port = 8000;
2+
export const host = '0.0.0.0';

api/app/index.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { createServer, ServerResponse, IncomingMessage } from 'http';
2+
3+
import { host, port } from './config/server.config';
4+
import { provideHeaders } from './providers/headers.provider'
5+
6+
function listener(
7+
req: IncomingMessage,
8+
res: ServerResponse<IncomingMessage>
9+
): void {
10+
req.method === 'GET' ?
11+
provideHeaders(res)
12+
.end(JSON.stringify({ message: 'Hello world!' })) :
13+
provideHeaders(res)
14+
.end(JSON.stringify({ data: 'Post request' }))
15+
}
16+
17+
const server = createServer(listener);
18+
19+
server.listen(port, host, () => {
20+
console.log(`Server listening on ${host}:${port}`);
21+
})
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { ServerResponse, IncomingMessage } from 'http';
2+
3+
type Response = ServerResponse<IncomingMessage>;
4+
5+
export function provideHeaders(response: Response): Response {
6+
return response
7+
.setHeader('Access-Control-Allow-Origin', '*')
8+
.setHeader('Date', (new Date(Date.now())).toUTCString())
9+
.setHeader('Server', 'CERN/3.0 libwww/2.17')
10+
.setHeader('Content-Type', 'application/json');
11+
}

api/package-lock.json

Lines changed: 74 additions & 21 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

api/package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@
1010
"author": "Andrey Skripachev",
1111
"license": "ISC",
1212
"dependencies": {
13+
"@types/cors": "^2.8.13",
14+
"@types/express": "^4.17.16",
15+
"@types/node": "^18.11.18",
1316
"typescript": "^4.9.4"
1417
}
1518
}

api/tsconfig.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,6 @@
1111
"forceConsistentCasingInFileNames": true,
1212
"rootDir": "app"
1313
},
14-
"include": [ "app/*" ],
14+
"include": [ "app/*", "app/core/models" ],
1515
"exclude": [ "node_modules" ]
1616
}

0 commit comments

Comments
 (0)