2020年3月8日 星期日

angular-使用 proxy 解決跨域請求問題

簡介

因為 angular 專案使用 nodeJS 建立開發環境,
不論將來是否打算將開發後的檔案與後端程式合併,
都會遇到瀏覽器阻擋跨域請求的問題。
當然方法之一是寫後端程式開放 Access-Control-Allow-Origin
另一個方法則是用 proxy 方式,讓 nodejs 幫您的 angular 代理 http request,
以避免跨域被擋的問題發生。
瀏覽器發送跨域請求(cross-site request)相關文章可以參考以下這兩篇 MDN 的文章

伺服器端存取控制(CORS)

跨來源資源共用(CORS)

1.更改 package.json

更改 package.json 檔案 "script" 結構下的 "start"

    start": "ng serve --proxy-config proxy.config.json",

2.新增 proxy.config.json

  1. 在專案資料夾底下新增 proxy.config.json 檔案。
  2. http://127.0.0.1:2020 為自己本基架設的 API Server(後端)
  3. http://localhost:4200 為 angular 專案預設 port (前端)
  4. 以下設定表示 angular 程式只要向 http://localhost:4200/apiServer 發送 http request,會經 nodejs 向http://127.0.0.1:2020 發送 request
  5. 如此便能解決瀏覽器阻擋的跨域請求問題

    {
         "/apiServer/*": { 
          "target": "http://127.0.0.1:2020",
          "secure": false,
          "changeOrigin": true,
          "pathRewrite": {
            "^/apiServer": ""
          }
        },
    }

3.啟動方式

請注意如果要使用 proxy,啟動方式就不再是 ng serve ,而要用 npm start 取代。

  npm start

4.HTTP Reauest

以下為發送請求範例片段程式。
如下所示,向自家 server http://127.0.0.1:4200/apiServer/apitest2 請求, nodejs 伺服器會代為發 proxy 向 http://127.0.0.1:2020/apitest2 做 http request

    ngOnInit(){
        let headers = new HttpHeaders({
          "Content-Type":"application/json",
        });
        this.http.post('apiServer/apitest2',{headers: headers}).subscribe(
          (val) => {
            debugger
          },
          response => {},
          () => {});
      }

5.範例程式下載

範例程式 : proxy
尚未準備完成,之後補上 XD

沒有留言:

張貼留言