问题 带有JSON数据的$ http.get()


我正在编写一个服务器应用程序,并希望客户端使用body中的数据来对我的GET方法进行pararmeterize,如下所示:

# http -v GET http://localhost:3000/url text=123 foo=bar
GET /url HTTP/1.1
Accept: application/json
Accept-Encoding: gzip, deflate, compress
Content-Length: 29
Content-Type: application/json; charset=utf-8
Host: localhost:3000
User-Agent: HTTPie/0.4.0

{
    "foo": "bar", 
    "text": "123"
}

在AngularJS中,我试过:

var params = {
    "foo": "bar", 
    "text": "123"
}

// no body
$http({
  method: 'GET',
  url: '/url',
  data: params })

// ugly url
// also has its limitation: http://stackoverflow.com/questions/978061/http-get-with-request-body
$http({
  method: 'GET',
  url: '/url',
  params: params })

// params in body, but I wanted GET
$http({
  method: 'POST',
  url: '/url',
  data: params })

这是设计还是错误?

我不明白为什么 文件


6779
2018-04-25 08:49


起源

你确定接收端是否支持它? 不禁止GET请求与机构,但也不是预期。 - bzlm
忘记文档,去研究GET在http中的含义。 - 7stud
GET方法不支持请求体 - Arun P Johny
我同意......你的问题的答案是“使用POST而不是” - 但由于这不是一个真正的答案,我不会冒险对我的代表。 - boisvert
总之,使用GET是不可能的,如果你想将json数据作为请求体发送,我建议你使用PUT或POST - Arun P Johny


答案:


我会以此为答案:

对于HTTP,它不是禁止的,但你不应该像服务器那样使用它(和 应该)忽略身体 GET 请求。

参考: 带请求正文的HTTP GET

对于XHR,身体 GET 和 HEAD 将被忽略(由@ jacob-koshy暗示)。

参考: https://xhr.spec.whatwg.org/#the-send()-method


11