前言
在写前端页面中,经常会在浏览器运行HTML页面,从本地文件夹中直接打开的一般都是file
协议,当代码中存在http
或https
的链接时,HTML页面就无法正常打开,为了解决这种情况,需要在在本地开启一个本地的服务器。
本文是利用node.js
中的http-server
,开启本地服务,步骤如下:
1 下载node.js
官网地址: https://nodejs.org
下载完成后在命令行输入命令$ node -v
以及$ npm -v
检查版本,确认是否安装成功。
zheng@zhengdeMBP ~ % node -v
v12.18.4
zheng@zhengdeMBP ~ % npm -v
6.14.6
2 下载http-server
在终端输入:
$ npm install http-server -g
zheng@zhengdeMBP lib % npm install http-server -g
/usr/local/bin/http-server -> /usr/local/lib/node_modules/http-server/bin/http-server
/usr/local/bin/hs -> /usr/local/lib/node_modules/http-server/bin/http-server
+ http-server@0.12.3
added 23 packages from 35 contributors in 6.533s
╭─────────────────────────────────────────────────────────────────╮
│ │
│ New patch version of npm available! 6.14.6 → 6.14.10 │
│ Changelog: https://github.com/npm/cli/releases/tag/v6.14.10 │
│ Run npm install -g npm to update! │
│ │
╰─────────────────────────────────────────────────────────────────╯
zheng@zhengdeMBP lib % ls
3 开启 http-server
服务
终端进入目标文件夹,然后在终端输入:
$ http-server -c-1 (⚠️只输入http-server的话,更新了代码后,页面不会同步更新)
Starting up http-server, serving ./
Available on:
http://127.0.0.1:8080
http://192.168.8.196:8080
Hit CTRL-C to stop the server
4 关闭 http-server
服务
按快捷键CTRL-C
终端显示^Chttp-server stopped.
即关闭服务成功。
另:MAC安全可能会出现的问题
zheng@zhengdeMBP ~ % npm install http-server -g
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! syscall access
npm ERR! path /usr/local/lib/node_modules
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR! [Error: EACCES: permission denied, access '/usr/local/lib/node_modules'] {
npm ERR! errno: -13,
npm ERR! code: 'EACCES',
npm ERR! syscall: 'access',
npm ERR! path: '/usr/local/lib/node_modules'
npm ERR! }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/zheng/.npm/_logs/2020-12-28T01_10_18_665Z-debug.log
解决办法
可以通过在文件夹上使用chown
解决问题:
sudo chown -R "$USER":admin /usr/local