Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$http.get() with JSON data

Tags:

http

angularjs

I'm writing a server app and wanted the client to use data in body to pararmeterize my GET method, like this:

# 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"
}

In AngularJS I tried:

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 })

Is this by design or a bug?

I cannot see why from the documentation.

like image 400
leesei Avatar asked Apr 25 '13 08:04

leesei


People also ask

Can we use JSON in GET request?

To get JSON from a REST API endpoint, you must send an HTTP GET request and pass the "Accept: application/json" request header to the server, which will tell the server that the client expects JSON in response.

How do I get HTTP response as JSON?

To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly.

How get JSON data from Fetch?

To get JSON from the server using the Fetch API, you can use the response. json() method. The response. json() method reads the data returned by the server and returns a promise that resolves with a JSON object.


1 Answers

I would take this as the answer:

For HTTP, it's not prohibited, but you shouldn't use it as the server may (and SHOULD) ignore the body of GET request.

Reference: HTTP GET with request body

For XHR, body of GET and HEAD will be ignored (hinted by @jacob-koshy).

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

like image 193
4 revs Avatar answered Sep 28 '22 13:09

4 revs