Windows 10 Nginx location API - IT 484

Windows 10 Nginx location API – IT 484

  • Post author:
  • Post category:IT / Nginx
  • Post comments:0 Comments
  • Post last modified:2023-01-13

當前後端團隊協同作業,同時開發時,常常會發生後端 API 實作尚未完成,而前端團隊已經開始同步進行作業,為了讓其他成員可以協同開發,減少等待後端團隊的時間,提升開發效率,所因應的方法。

功能簡介

Nginx 是一個異步框架的網頁伺服器,用於處理併發請求,整體是採用模組化設計,組態檔案也非常簡潔容易設定,同時也提供了反向代理、負載平衡器、HTTP 快取等功能,相較於 Apache、lighttpd 具有占有內存少,穩定性高等優勢,能保持低資源低消耗高性能,在網際網路項目中廣泛應用。

主機架構

模擬一個網域,綁定本機。

Domain IP Port
ggg.cc 127.0.0.1 10090

組態設定

Windows 10 Nginx location config

開啟檔案總管,編輯檔案。

C:\nginx\conf\conf.d\location-api.conf

server {
    listen 10090;
    server_name ggg.cc;
	
    location = /login {
        default_type application/json;
        return 200 '{"errorCode":0,"name":"player","token":"0x12345678"}';
    }
    
    location = /user {
        default_type application/json;
        return 200 '{"errorCode":0,"name":"player"}';
    }

    location = /users {
        default_type application/json;
        return 200 '{"errorCode":0,"names":[player, player2]}';
    }

    location = /logout {
        default_type application/json;
        return 200 '{"errorCode":0}';
    }
	
    location = /exist {
        default_type application/json;
        return 200 '{"errorCode":0,"exist":false}';
    }
	
    error_page  405     =200 $uri;
}

網域導向

開啟檔案總管,編輯檔案。

C:\Windows\System32\drivers\etc\hosts

127.0.0.1 ggg.cc

運行管理

服務熱載入

修改設定檔後,使用 nginx reload 重新載入設定,立即生效。

cd C:\nginx
nginx -s reload

停止服務

啟動服務後,使用 nginx stop 命令終止服務運行。

cd C:\nginx
nginx -s stop

狀態驗證

Nginx location directive

命令提示字元,查看服務狀況。

tasklist /fi "imagename eq nginx.exe"

映像名稱                       PID 工作階段名稱      工作階段 #    RAM使用量
========================= ======== ================ =========== ============
nginx.exe                     1868 Console                   18      7,296 K
nginx.exe                     1464 Console                   18      7,328 K
nginx.exe                    10424 Console                   18      7,344 K
nginx.exe                      128 Console                   18      7,320 K
nginx.exe                    13168 Console                   18      7,308 K
nginx.exe                    13956 Console                   18      7,340 K
nginx.exe                     2316 Console                   18      7,348 K

測試 Postman

網址: http://ggg.cc:10090/login

IT 484 Windows 10 Nginx location API login

網址: http://ggg.cc:10090/user

IT 484 Windows 10 Nginx location API user

網址: http://ggg.cc:10090/logout

IT 484 Windows 10 Nginx location API logout

心得分享

通常工作流程,可能都會等後端開發完成後,通知前端,前端再拿 API 來串接,但這樣的流程前端就必須等待後端,如果用 Nginx 模擬 API,先定義好前後溝通的規格,傳回假資料如: JSON 格式資料,那麼前後端就能各自按照規格進行開發,等 API 完成實作後,就可以使用 Nginx proxy_pass 來導向到真正的 AP 服務。

發佈留言