You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

前端发送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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 22:58:13