前端能否实现 GET 请求 通过 Body 来发送数据 ?

3,572 阅读1分钟

对网络上的结果进行收集,准确度方面,应该没什么问题

如果仅限制在浏览器

  1. XMLHttpRequest
    xhr的规范 image.png

依照规范,如果是 get 请求,body 中的数据会被置为 null

  1. axios github 上的讨论

The spec doesn't forbid it indeed but it's not supported by axios for the moment. Could you consider creating a PR for this? ,意思是 规范上没禁止,但是 axios 现在没支持,欢迎大家提 PR..

  1. Fetch

fetch 也是不支持的. 会有这种报错 Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.

Fetch 规范

  1. 待验证的
  • angular 中的 httpmodule (angular 不了解...)

ok ,看样子 目前如果只是在浏览器层面,似乎是不大好实现的,那么如果我们把限制放宽一点呢

其他的方式

  1. node 可以实现吗? 根据查到的资料,应该没什么问题
request.get('http://localhost:8092/_search', {  
  json: true,    
  body: {
    "query": {
        "more_like_this" : {
            "fields" : ["title", "description"],
            "like" : "Once upon a time",
            "min_term_freq" : 1,
            "max_query_terms" : 12
        }
    }
  }
})
  1. curl 可以吗? 看了下 大佬的文章 应该也没啥问题

7.postman

postman 旧版本不支持,但是 从 7.20.1 开始,就开始支持了

为什么写这篇文章

  1. 有的面试会问,记在脑子里总是会忘掉
  2. 探寻 并且记录一下

总结

  1. 规范不支持,但是没说完全不能这样子用,想用就用,约定好就行
  2. 我觉得这个规范不够自由,或者说不够合理,或许在之后的某一天,会发生改变(一个比较正常的思维是,你可以说不推荐这么做,但是不能把这条路堵得比较死)
  3. 晚饭吃的有点饱 准备回家(凑数的,我喜欢 3 )