盤點Mac上搭建本地WebServer的幾種方式


第一種: 通過Nginx搭建本地WebServer

安裝nginx

brew install nginx

安裝完后在終端輸入nginx指令,啟動nginx查看效果

確定安裝好之后,在根目錄創建一個文件夾MyServer,以后文件啥的直接往里扔,通過這個目錄去訪問

cd 
mkdir MyServer

修改配置文件nginx.conf,brew安裝的nginx配置文件路徑默認在/usr/local/etc/nginx/nginx.conf

sudo vim  /usr/local/etc/nginx/nginx.conf

打開配置文件之后,在43行附近,添加一個路由映射,也就是關聯上之前創建的那個目錄MyServer

# 書寫✍️格式
     location /自定義路由名/ {
            alias 映射本地路徑 ;
       }
       
# 根路由一般情況下不必去修改它
  location / {
            root   html;
            index  index.html index.htm;
     }

# 自己映射一個路由路徑
        location /test/ {
            alias /Users/username/MyServer/;
        }
# 編輯完保存配置,重啟或者刷新配置才會生效

sudo nginx -s reload #刷新配置
sudo brew services restart nginx #重啟服務

MyServer丟一些文件文本啥的,然后啟動nginx去訪問,查看具體效果如何

nginx常用的幾條命令:

# 啟動
nginx

# 刷新配置
sudo nginx -s reload

# 重啟服務
sudo brew services restart nginx 或者 sudo nginx -s restart

# 停止服務
sudo brew services stop nginx 或者 sudo nginx -s stop

# 查看啟動情況
ps -ef|grep nginx
 

第二種 Mac自帶的apahe

其實Mac自帶apache服務,只是需要一個起手式就能開啟服務

#!/bin/bash
webServer() {
    echo "======================================"
	echo "請選擇需要執行的apache命令選項"
	echo "0. 開啟apache "
	echo "1. 重啟apache"
	echo "2. 關閉apache"
	echo "3. 部署目錄或者文件到apache根目錄"
	echo "======================================"
	
	read -p "輸入選項編號:" number
	case $number in 
		0) startApache	
		;;
			
		1) restartApache	
		;;
		
		2) stopApache	
		;;

		3) movePathToApache	
		;;

	esac	
 }
#開啟
startApache (){
	sudo /usr/sbin/apachectl start
}
#重啟
restartApache (){
	sudo /usr/sbin/apachectl restart
}
#停止
stopApache (){
	sudo /usr/sbin/apachectl stop
}

#部署
movePathToApache (){
	read -p "輸入需要部署的項目路徑: " root_proj_dir
	webServer_dir="/Library/WebServer/Documents" 
	sudo cp -R ${root_proj_dir} ${webServer_dir}
	echo "已部署至127.0.0.1目錄下"
	open /Library/WebServer/Documents
}

####################################################
webServer

第三種 Node.js 不過需要通過寫代碼來實現

首先得先安裝node環境
其次參考github上的demo

git clone https://wwww.github.com/WangGuibin/FlutterStudyDailyCase.git
cd node_server
npm install
npm start
# 路由在config.js中配置 公共文件夾是public即根路由 
# 接口編寫參考`testData.js` 的寫法

第四種 使用Dart語言編寫

具體可參考

git clone https://wwww.github.com/WangGuibin/FlutterStudyDailyCase.git
cd  dart_webserver
#除了pubspec.yaml 其實就一個main.dart文件而已 

第五種 使用Python建立臨時本地服務(最簡單)

默認端口是8080

# python2.7
 python -m SimpleHTTPServer 8081
# python3.x. 
 python3 -m http.server 8888 --bind 127.0.0.1

# 默認是在根目錄 打開之后可以通過瀏覽器訪問你的目錄文件

目前掌握的,先就是這些了 _ 以后有機會接觸到其他的再更新.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM