"Method?Not?Allowed"405問題分析以及解決方法
首先,明確一點(diǎn)405問題就是瀏覽器端(或客戶端)請求方法和服務(wù)端處理該路徑的請求的處理方法不一致造成的。
背景:
SpringBoot2.70整合JPA,測試單表的增刪改查
現(xiàn)象:
在用postman測試delete方法的時(shí)候遇到的
圖1: postman測試截圖
圖2:后端代碼塊
package com.xxxx.salesforecast.Controller; import com.xxxx.salesforecast.pojo.User; import com.xxxx.salesforecast.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 用戶外部接口 * * @author : liuke * @date : 2022-06-22 14:20 **/ @RestController @RequestMapping("/user") public class UserController { @Autowired private UserRepository userRepository; /** * 插入 * * @param user * @return */ @PostMapping public String addUser(@RequestBody User user) { userRepository.save(user); return "success"; } /** * 查詢?nèi)? * * @return */ @GetMapping("") public List<User> getAllUser() { List<User> userList = userRepository.findAll(); return userList; } /** * 根據(jù) id 刪除 * @param id * @return */ @DeleteMapping("/{id}") public String deleteUserById(@PathVariable Integer id){ userRepository.deleteById(id.intValue()); return "success"; } }
圖三:控制臺報(bào)錯(cuò)
排查解決過程:
第一步:大致檢查一下自己代碼,感覺沒問題,開始百度
第二步:百度得到的第一個(gè)方案,未解決
application.yml中添加spring mvc: hiddenmethod: filter: enabled: true
這個(gè)啟動HiddenHttpMethodFilter過濾器,以支持瀏覽器可以發(fā)送DELETE PUT 請求。而我沒用瀏覽器發(fā)送請求,而是用postman,所以無用也正常。
第三步:嘗試將@DeleteMapping改成@RequestMapping,未解決
第四步:嘗試去掉@PathVariable 注解,未解決
第五步:想到,我用的是restful接口,增刪改查的路徑都是一樣,通過@PostMapping、@PutMapping、@DeleteMapping、@GeMapping來區(qū)分行為。
于是修改了方法的路徑,還是不行。但是這個(gè)時(shí)候不報(bào)405了,開始報(bào)404了。
404,眾所周知一定是沒有匹配的路徑。
然后我終于發(fā)現(xiàn)了問題的所在,下圖路徑
http://localhost:6060/user/delete?id=1
這里的id是以傳參的形式
而@DeleteMapping(“/delete/{id}”)的意思是id當(dāng)路徑
所以路徑改成
思考:那為什么之前都會報(bào)405的錯(cuò)誤呢?
因?yàn)槠ヅ涞搅瞬樵兊慕涌?,這個(gè)接口就是@GetMapping,所以和@DeleteMapping并不一致,就報(bào)了405錯(cuò)誤。
且這個(gè)接口不需要傳參,如果傳參了也是不會報(bào)錯(cuò)的,比如,我們訪問http://baidu.com 和 http://baidu.com/?sbbaidu=1是一樣的
總結(jié):
題出在我把@DeleteMapping(“/{id}”)的id當(dāng)路徑和路徑傳參弄混了。
到此這篇關(guān)于"Method Not Allowed"405問題分析以及解決方法的文章就介紹到這了,更多相關(guān)Method Not Allowed 405問題內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
spring mail借助qq郵箱服務(wù)器發(fā)送郵件
這篇文章主要介紹了spring mail借助qq郵箱服務(wù)器發(fā)送郵件的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12j2ee mybatis注解@Data,@TableName,@TableField使用方式
這篇文章主要介紹了j2ee mybatis注解@Data,@TableName,@TableField使用方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-04-04SpringBoot整合Mybatis簡單實(shí)現(xiàn)增刪改查
這篇文章主要介紹了SpringBoot整合Mybatis簡單實(shí)現(xiàn)增刪改查,文章為圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08