前端发送HTTP请求报400错误,手动请求API正常的原因排查
解决前端POST请求返回400(Bad Request)错误的问题
问题根源
你代码里的请求URL用双引号包裹,导致模板字符串的变量插值语法${username}、${password}没有被解析,直接作为静态字符串拼接到URL中,后端收到的参数是字面量${username}和${password},不符合接口要求,因此返回400错误。
修复方案
将包裹URL的双引号替换为反引号(`),模板字符串只有用反引号包裹才能正确解析变量:
document.getElementById("signupbtn").addEventListener("click", function(){ 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(); })
额外建议
如果后端接口要求POST参数放在请求体而非URL查询参数中,可调整代码如下(以表单格式为例):
document.getElementById("signupbtn").addEventListener("click", function(){ const username = document.getElementById("username").value; const password = document.getElementById("password").value; const xhr = new XMLHttpRequest(); xhr.open("POST", "http://localhost:9000/user/register"); // 设置请求头,告知后端参数格式 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // 将参数放在请求体中发送 xhr.send(`username=${username}&password=${password}`); })
内容的提问来源于stack exchange,提问作者MatildaEliz
相关产品推荐
相关产品推荐

