This article explains how to set up a simple local testing server on your machine, and the basics of how to use it.
| Prerequisites: | You need to first know how the Internet works ,和 what a Web server is . |
|---|---|
| Objective: | You will learn how to set up a local testing server. |
Throughout most of the learning area, we tell you to just open your examples directly in a browser — this can be done by double clicking the HTML file, dragging and dropping it into the browser window, or choosing File > 打开... and navigating to the HTML file. There are many ways to achieve this.
If the web address path starts with
file://
followed by the path to the file on your local hard drive, a local file is being used. In contrast, if you view one of our examples hosted on GitHub (or an example on some other remote server), the web address will start with
http://
or
https://
, to show that the file has been received via HTTP.
Some examples won't run if you open them as local files. This can be due to a variety of reasons, the most likely being:
file://
schema as cross-origin requests.
So if you load a local file that includes other local files, this may trigger a
CORS
错误。
To get around the problem of async requests, we need to test such examples by running them through a local web server.
One of the easiest ways to do this for our purposes is to use Python's
http.server
模块。
注意:
Older versions of Python (up to version 2.7) provided a similar module named
SimpleHTTPServer
. If you are using Python 2.x, you can follow this guide by replacing all uses of
http.server
with
SimpleHTTPServer
. However, we recommend you use the latest version of Python.
To do this:
python -V
# If the above fails, try:
python3 -V
# Or, if the "py" command is available, try:
py -V
cd
命令。
# include the directory name to enter it, for example
cd Desktop
# use two dots to jump up one directory level if you need to
cd ..
# If Python version returned above is 3.X
# On Windows, try "python -m http.server" or "py -3 -m http.server"
python3 -m http.server
# If Python version returned above is 2.X
python -m SimpleHTTPServer
localhost:8000
in your web browser. Here you'll see the contents of the directory listed — click the HTML file you want to run.
注意:
If you already have something running on port 8000, you can choose another port by running the server command followed by an alternative port number, e.g.
python3 -m http.server 7800
(Python 3.x) or
python -m SimpleHTTPServer 7800
(Python 2.x). You can then access your content at
localhost:7800
.
Python's
http.server
(或
SimpleHTTPServer
for Python 2) module is useful, but it is merely a
static
file server; it doesn't know how to run code written in languages such as Python, PHP or JavaScript. To handle them, you'll need something more — exactly what you'll need depends on the server-side language you are trying to run. Here are a few examples:
$ cd path/to/your/php/code
$ php -S localhost:8000
最后修改: , 由 MDN 贡献者