含義
- POST、DELETE、PUT、GET 就像對應着數據庫的 CRUD(增、刪、改、查)
使用標準:
POST /uri 創建
GET /uri/xxx 查詢
PUT /uri/xxx 更新或創建
DELETE /uri/xxx 刪除
GET請求,用於向服務器發送查詢數據的請求,只是查詢,不會增加、修改數據,不會影響服務器上資源的內容。無論進行多少次都,執行後的結果都是一樣的,具有冪等性。
PUT請求,是用於向服務器發送數據,從而改變數據,修改數據內容。但是不會增加數據的種類。無論進行多少次操作,其結果也都一樣,具有冪等性。
POST請求,與PUT請求類似。都是向服務器端發送數據,但是改請求會增加數據的種類,創建新的內容。不具有冪等性。
DELETE請求,用來刪除某一資源。
冪等性:冪等意味着對同一個URL的多次請求會返回一樣的結果
使用
- POST
// 前端發起POST請求 const {data:res} = await this.$http.post("addUser", this.addForm);
// 後臺接收POST請求 @RequestMapping("/addUser") public String addUser(@RequestBody User user) { System.out.println(user); user.setRole("普通用戶"); user.setState(false); int i = userDao.addUser(user); String str = i > 0 ? "success" : "error"; return str; }
- GET
// 前端發起GET請求 const {data:res} = await this.$http.get("getUpdate?id=" + id);
// 後臺接收GET請求 @RequestMapping("/getUpdate") public String getUpdateUser(int id) { System.out.println("編號:" + id); User updateUser = userDao.getUpdateUser(id); String users_json = JSON.toJSONString(updateUser); return users_json; }
- PUT
// 前端發起PUT請求 const {data:res} = await this.$http.put("editUser", this.editForm);
// 後臺接收PUT請求 @RequestMapping("/editUser") public String editUser(@RequestBody User user){ System.out.println(user); int i = userDao.editUser(user); String str = i > 0 ? "success" : "error"; return str; }
- DELETE
// 前臺發起DELETE請求 const {data:res} = await this.$http.delete("deleteUser?id=" + id);
// 後臺接收DELETE請求 @RequestMapping("/deleteUser") public String deleteUser(int id) { System.out.println(id); int i = userDao.deleteUser(id); String str = i > 0 ? "success" : "error"; return str; }
注意
- 一般我們需要提交表單在 Vue 中需要表單驗證
// 表單驗證 this.$refs.editFormRef.validate(async valid =>{ console.log(valid); if( !valid ) { return; } // 發起請求 const {data:res} = await this.$http.put("editUser", this.editForm); console.log(res); if (res != "success") { return this.$message.error("操作失敗!!!"); } this.$message.success("操作成功!!!"); // 隱藏修改對話框 this.editDialogVisible = false; this.getUserList(); });
有興趣的同學可以關注我的個人公衆號,期待我們共同進步!!!