--- title: Http Request tags: JAVA, Rest --- ## Java Backend ### Request Method * RequestMapping("/asset") 此種寫法的情境下,不論是透過 Get 或是 Post 送出路徑為 "/asset" 的請求,都會對應到同樣的 Controller。 Get Method 以及 Post Method 並沒有硬性規定必須依功能區分使用,如 Get 只能讀取、 Post 只能新增,兩者差別只在於傳遞資料的方式不同,也因為各自的傳遞資料特性,有較適合的使用時機。 * Get 使用直接加在請求路徑(網址)的方式傳遞資料 1. Request Param - 請求參數 ex. 前端送出 `/asset?編號=1&名稱=SmartPole#1` 的請求 上述的寫法於後端接收時會指定資料的 key (資料的名稱) ``` @RequestMapping("/asset") @RequestParam(name = "編號") int id, @RequestParam(name = "名稱") string name ``` 2. Path Variable - 路徑變數 ex. 前端送出 `/asset/1/SmartPole#1` 的 請求 後端則用以下方式接收 ``` @RequestMapping("/asset/{id}/{name}") @PathVariable(name = "id") int id, @PathVariable(name = "name") string name, ``` * API Document 常用變數表示方式: 1.`/asset/:id` 2.`/asset/{id}` * Post 則是透過 Path Variable( 通常用於指定目標 ) & Method (將資料放在 Message Body ) 傳遞資料 (通常為 JSON 格式),傳遞資料的格式需透過 Http Header 定義,ex. `Content-Type: application/json`。 前端常用 Method * JSON.parse("json") - JSON 轉換成 Object * JSON.stringify(data) - Object 轉換成 JSON ### Restful * Post ( C ) - 新增 1. 新增一筆 asset 資料 - `Post - /asset` * Get ( R ) - 查詢 1. 查詢多筆(全部) asset 資料 - `Get - /asset` 2. 查詢主鍵 (Primary Key) 為 1 的 asset - `Get - /asset/1` * Put / Post ( U ) - 修改 1. 修改多筆(全部) asset 資料 - `Put/Post - /asset` 2. 修改主鍵為 1 的 asset 資料 - `Put/Post - /asset/1`,若不存在此筆資料,則回傳錯誤 * Delete ( D ) - 刪除 1. 刪除多筆(全部) asset 資料 - `Delete - /asset` 2. 修改主鍵為 1 的 asset 資料 - `Delete - /asset/1`,若不存在此筆資料,則回傳錯誤 ## AJAX ( Asynchronous JavaScript and XML ) ## References [HttpChallenge](https://lidemy-http-challenge.herokuapp.com/start) [API List 範例](https://gist.github.com/aszx87410/3873b3d9cbb28cb6fcbb85bf493b63ba) [AJAX](https://tw.alphacamp.co/blog/ajax-asynchronous-request)