# RL-?? API 可以在Controller 輸出render成 JSON,輕鬆取得JSON格式資料。 ```ruby= def index @users = User.all render json: @users end ``` ## respond_to 要同時可以呈現 HTML 跟 JSON。 ```ruby= 使用 respond_to 可以針對**不同的格式(html 或 json)**,輸出不同的結果。 def index @users = User.all respond_to do |format| format.json { render json: @users } format.html { render :index } end end ``` ## JBuilder 要同時可以呈現 HTML 跟 JSON。 若使用 Scaffold 會產生 一些.json.jbuilder 檔案。 # API-Only 模式 減少產生不必要檔案。 建立新專案時,尾巴加「--api」: ``` rails new my_blog --api ``` ## h2 - fetch: 使用非同步,會去 Web API 排隊,預設用get去抓東西 fetch 回傳 promise 用 then 來做事,繼續往下做 用 json 函式解讀,會回傳 promise 可以再繼續用 then 做事 resp 是 fetch 的結果 data 是 then 的結果 回傳 username ```javascript= fetch("https://jsonplaceholder.typicode.com/users") .then((resp) => resp.json()) // Promise .then((data) => { for (let { username } of data) { console.log(username); } // data.forEach((d) => { // console.log(d.username); // }); }); ``` ### API(Application Programming Interface): 重點在介面,現在演變成網路服務,回傳 JSON #### Endpoint: 資料傳輸接點 = 請求的資源本身 .com/後面的字是 Endpoint 前面指的是那個網址本體,後面的 Endpoint 代表橋梁,負責接收傳遞資料 - 設計: - 讓使用者清楚知道是 api: POST /api/note/2/favorite - 加版本會更好,如果要更新會比較有彈性: POST /api/v2/note/2/favorite ### axios [axios](https://github.com/axios/axios) 打 api 的套件,因為 JS 的 fetch 太陽春了,用 axios 會比較方便 用 yarn add axios 安裝 網站上線後還是要抓東西,所以 axios 會放在 dependencies - package.json - dependencies:會上線的放這 - devDependencies:不會上線的放這 ### csrf 跨站請求偽造 對方寄連結給你,借你的權限來做事 csrf token:防止 csrf 的發生,因為對方沒有 token 還是一樣沒用,不能借你的權限來做事 ###### tags: `Rails`