http-server设置允许跨域

记录一次http-server开启允许跨域设置的过程,多多沉淀,防止遗忘。

前端发展到今天,http-server基本是每个前端都会接触到的npm包了,它简洁轻量,只需要在终端一行简单代码就可以开启一个静态文件服务器。

启动服务

http-server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$ npx http-server
Starting up http-server, serving ./

http-server version: 14.1.1

http-server settings:
CORS: disabled
Cache: 3600 seconds
Connection Timeout: 120 seconds
Directory Listings: visible
AutoIndex: visible
Serve GZIP Files: false
Serve Brotli Files: false
Default File Extension: none

Available on:
http://127.0.0.1:8080
Hit CTRL-C to stop the server

查询内置文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
$ npx http-server -h
usage: http-server [path] [options]

options:
-p --port Port to use. If 0, look for open port. [8080]
-a Address to use [0.0.0.0]
-d Show directory listings [true]
-i Display autoIndex [true]
-g --gzip Serve gzip files when possible [false]
-b --brotli Serve brotli files when possible [false]
If both brotli and gzip are enabled, brotli takes precedence
-e --ext Default file extension if none supplied [none]
-s --silent Suppress log messages from output
--cors[=headers] Enable CORS via the "Access-Control-Allow-Origin" header
Optionally provide CORS headers list separated by commas
-o [path] Open browser window after starting the server.
Optionally provide a URL path to open the browser window to.
-c Cache time (max-age) in seconds [3600], e.g. -c10 for 10 seconds.
To disable caching, use -c-1.
-t Connections timeout in seconds [120], e.g. -t60 for 1 minute.
To disable timeout, use -t0
-U --utc Use UTC time format in log messages.
--log-ip Enable logging of the client's IP address

-P --proxy Fallback proxy if the request cannot be resolved. e.g.: http://someurl.com
--proxy-options Pass options to proxy using nested dotted objects. e.g.: --proxy-options.secure false

--username Username for basic authentication [none]
Can also be specified with the env variable NODE_HTTP_SERVER_USERNAME
--password Password for basic authentication [none]
Can also be specified with the env variable NODE_HTTP_SERVER_PASSWORD

-S --tls --ssl Enable secure request serving with TLS/SSL (HTTPS)
-C --cert Path to TLS cert file (default: cert.pem)
-K --key Path to TLS key file (default: key.pem)

-r --robots Respond to /robots.txt [User-agent: *\nDisallow: /]
--no-dotfiles Do not show dotfiles
--mimetypes Path to a .types file for custom mimetype definition
-h --help Print this list and exit.
-v --version Print the version and exit.

开启cors

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
npx http-server --cors
Starting up http-server, serving ./

http-server version: 14.1.1

http-server settings:
CORS: true
Cache: 3600 seconds
Connection Timeout: 120 seconds
Directory Listings: visible
AutoIndex: visible
Serve GZIP Files: false
Serve Brotli Files: false
Default File Extension: none

Available on:
http://127.0.0.1:8080
Hit CTRL-C to stop the server