get 请求中如何携带 body 参数


先说结果, 浏览器中不能带.

https://github.com/axios/axios/issues/787

  • fetch
fetch("/users", {
  method: "GET",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Hubot", login: "hubot" })
});

得到报错:

Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.

具有 GET/HEAD 方法的请求不能有 body.

  • xhr
var a = new XMLHttpRequest();
a.open("GET", "/");
a.send("testBody");

xhr 没有成功发送 testBody 参数.

总结

浏览器当前的实现是不允许 get 发送 body, 但后端应用通常可以发送. 比如 nodejs 或 postman .

所以, 如果是自己的程序. 最好按规范来,不要在 get 里传 body, 如果是第三方API, 无法更改, 那么可以用后端服务转发一下. 因为前端不能使用 get 方法从浏览器里发送 body.


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM