Skip to content

Commit 5eff516

Browse files
committed
feat: cli input cors
1 parent 1a22483 commit 5eff516

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

src/cli.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@ const cliOptions = [
2222
defaultValue: '',
2323
usage: `htttp-server --data ./data/data.json`,
2424
},
25+
{
26+
option: '--cors',
27+
description: 'Enable cors',
28+
defaultValue: false,
29+
usage: `htttp-server --cors`,
30+
},
2531
];
2632

2733
cliOptions.forEach(({ option, description, defaultValue }) => program.option(option, description, defaultValue.toString()));
@@ -35,8 +41,9 @@ program.parse(process.argv);
3541
const opts = program.opts();
3642

3743
const server = new Server({
38-
port: opts.port,
44+
port: Number(opts.port),
3945
baseDir: opts.directory,
4046
dataPosition: opts.data,
47+
cors: JSON.parse(opts.cors),
4148
});
4249
server.start();

src/index.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ export default class Server {
1515
port: number = DEFAULT_PORT;
1616
baseDir: string = DEFAULT_BASE_DIR;
1717
data: { [k: string]: ResourceItem[] } = {};
18+
cors: boolean = false;
1819

1920
constructor(options?: ServerOptions) {
2021
if (options?.port) {
@@ -32,11 +33,16 @@ export default class Server {
3233
} else {
3334
this.data = DEFAULT_DATA;
3435
}
36+
if (options?.cors) {
37+
this.cors = true;
38+
}
3539
}
3640

3741
start() {
3842
const server = http.createServer(async (req, res) => {
39-
this.processCors(req, res);
43+
if (this.cors) {
44+
this.processCors(req, res);
45+
}
4046
try {
4147
const requestUrl = decodeURIComponent(req.url ?? '/');
4248
if (requestUrl.startsWith(API_PREFIX)) {

src/types.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ export interface ServerOptions {
44
port?: number;
55
baseDir?: string;
66
dataPosition?: string;
7+
cors?: boolean;
78
}
89

910
export type Res = http.ServerResponse<http.IncomingMessage> & {

0 commit comments

Comments
 (0)