Axios发送GET请求时无法将body参数传递到后端API该如何处理?
问题解决方案
根本原因
HTTP 规范本身不建议 GET 请求携带请求体,绝大多数浏览器的 XMLHttpRequest 实现会主动丢弃 GET 请求的请求体内容,Axios 底层基于 XMLHttpRequest 封装,因此默认不会处理 GET 请求传入的 body 参数,这就是后端拿到空对象的核心原因。而 Insomnia 等接口测试工具没有遵循这一浏览器限制,因此可以正常传递 GET 请求的请求体。
最优解决方案(推荐):将请求改为 POST 方法
登录属于提交敏感数据的操作,本身就不适合用 GET 方法实现,改为 POST 即可完美解决问题,修改方法如下:
1. 后端Express接口修改
首先确保你的Express服务已经开启了JSON解析中间件(一般在入口文件配置):
// Express 4.16+ 版本自带JSON解析中间件,无需单独安装body-parser app.use(express.json())
然后修改接口的请求方法:
// 把get改成post router.post('/login', async function(req,res) { try { const email = req.body.email; const pass = req.body.pass; const users = await pool.query("select username from users where username=$1 and password=$2", [email, pass]); if(users.rows[0]) res.json(users.rows[0]['username']!=null); else res.json(users) console.log(req.body) console.log(email,pass) } catch (err) { console.log(err.message); } });
2. 前端Axios请求修改
Axios的post方法会自动序列化传入的对象为JSON,无需手动调用JSON.stringify,也无需手动设置Content-Type:
async function GetData() { const email = document.getElementById("email").value; const pass = document.getElementById("pass").value; const response = await axios.post("http://localhost:3002/login", // post方法第二个参数直接传请求体对象即可 {"email": email, "pass" : pass}) console.log(response.config.data); console.log(response.data) }
兼容方案(不推荐):坚持用GET请求的处理方式
如果由于特殊原因必须使用GET请求,那么不要用请求体传参,改为通过URL查询参数传递:
1. 后端接口修改
改为从req.query获取参数:
const email = req.query.email; const pass = req.query.pass;
2. 前端Axios请求修改
通过params字段传递参数,Axios会自动将参数拼接到URL上:
async function GetData() { const email = document.getElementById("email").value; const pass = document.getElementById("pass").value; const response = await axios.get("http://localhost:3002/login", { params: {"email": email, "pass" : pass} }) console.log(response.config.params); console.log(response.data.rows) }
注意:该方案会将密码明文暴露在URL中,会被浏览器历史、服务器日志等记录,存在严重安全风险,仅做兼容参考,生产环境禁止使用。
内容的提问来源于stack exchange,提问作者Slurpee Sauce
相关产品推荐
相关产品推荐

