有關Fetch與axios與跨域請求

有關Fetch

https://developer.mozilla.org/zh-TW/docs/Web/API/Fetch_API/Using_Fetch

以前用xmlHttprequest但寫法太多,fetch為比較簡潔的寫法,並且有then可使用

注意事項:

1.使用json()轉換or其他型態轉換回傳資料e.g. text(), blob() ...https://developer.mozilla.org/en-US/docs/Web/API/Body

2.第二個then才拿得到資料,第一個then只是一個promise結果

3.cookie要手動在header加入(第二個參數)

     fetch('http://localhost:3001/getArticle',{
           method: 'GET',
       })
       .then((response) => {
           if (response.status >= 200 && response.status < 300) {
               return response.json();
           } else {
               var error = new Error(response.statusText)
               error.response = response;
               throw error;
           }
       })
       .then((data) => {
         console.log(data)
       })
       .catch(function(error) {
           console.log('request failed', error);
           return error.response.json();
       })

https://www.reddit.com/r/learnprogramming/comments/3ydnmn/javascriptnodejswhatwgfetch_why_does_this_return/

使用POST

如果要傳JSON要先stringify

Fetch 取得 server 錯誤訊息

https://github.com/github/fetch/issues/203#issuecomment-335786498

Axios

https://github.com/mzabriskie/axios

也是一個可發request的套件

如果要抓取error message要使用如下

https://github.com/mzabriskie/axios/issues/376

#Get 範例

#POST x-www-form-urlencoded範例

注意:

如果是要發送cookie記得要加上 withCredentials: true

或是直接寫為default

然後server的Cross domain要設定

記得Origin不可用*

不然會顯示如下訊息.

#瀏覽器跨域請求

因為瀏覽器發出的請求會被限制同網域 不像後端server或是chrome plugin可以對其他網域請求

所以我們可以用https://crossorigin.me這類的proxy服務

如果是要往自己的server發request可以參考JSONP或在server設定CORS

或是使用chrome相關plugin

下載檔案

記得加上

Last updated

Was this helpful?