发起HTTP POST请求却收到405错误(Method 'GET'不支持)如何解决?
问题原因及解决办法
核心问题:表单默认提交行为干扰
你的按钮大概率是<button type="submit">,或是嵌套在未指定提交方式的<form>标签内,点击时会触发表单默认GET请求,和你通过XHR发起的POST请求冲突。服务器实际收到了GET请求,但你的接口仅支持POST,因此返回405错误。
解决步骤
1. 阻止表单默认提交行为
修改JS代码,在点击事件中添加event.preventDefault(),阻断默认的表单提交逻辑:
document.getElementById("signupbtn").addEventListener("click",function(event){ // 阻止表单默认提交 event.preventDefault(); const username = document.getElementById("username").value; const password = document.getElementById("password").value; const xhr = new XMLHttpRequest(); xhr.open("POST","http://localhost:9000/user/register?username="+username+"&password="+password); xhr.send(); })
或者直接修改按钮类型为button,从根源避免触发表单提交:
<button id="signupbtn" type="button">注册</button>
2. 规范POST请求参数传递(可选但推荐)
POST请求通常将参数放在请求体中而非URL,更符合REST规范且安全性更高,可按以下方式调整:
前端JS(用FormData传递参数):
document.getElementById("signupbtn").addEventListener("click",function(event){ event.preventDefault(); const username = document.getElementById("username").value; const password = document.getElementById("password").value; const formData = new FormData(); formData.append("username", username); formData.append("password", password); const xhr = new XMLHttpRequest(); xhr.open("POST","http://localhost:9000/user/register"); xhr.send(formData); })
后端优化方案(可选)
如果想更规范地通过请求体接收参数,可创建DTO类并使用@RequestBody:
// 新建UserDTO类 public class UserDTO { private String username; private String password; // 生成getter、setter方法 } // 修改Controller方法 @PostMapping("/register") ResponseEntity<String> addUser(@RequestBody UserDTO userDTO) { userService.addUser(userDTO.getUsername(), userDTO.getPassword()); return ResponseEntity.ok("User added succesfully"); }
3. 验证请求有效性
可在XHR中添加回调监听,确认请求实际发送情况:
xhr.onload = function() { console.log("请求状态码:", xhr.status); console.log("响应内容:", xhr.responseText); };
内容的提问来源于stack exchange,提问作者MatildaEliz
相关产品推荐
相关产品推荐

