Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 http GET with Body?

Tags:

angular

get

I'm querying some elasticsearch servers from my Angular2 site. To help with security, we'd like to lock down access to only GET requests. Elasticsearch supports GET with a body but I'm having troubles making it happen with Angular2's http class.

this.http.post(SearchEndpoint, q.BuildPayload(), { method: 'GET' })

Since http.get doesn't have a body parameter, I am trying to use the post method. Previously I would leave off the RequestOptionsArgs of { method: 'GET' } and the POST would go through successfully with the body. By specifying the method in the third parameter the http class removes the body from the request.

Is it possible to make a GET request with a body in Angular 2?

like image 814
Corey Ogburn Avatar asked Feb 03 '16 18:02

Corey Ogburn


1 Answers

I think that the raw XHR object doesn't allow this. To quote the specification (see https://xhr.spec.whatwg.org/):

4.5.6 The send() method

client . send([body = null])

Initiates the request. The optional argument provides the request body.

The argument is ignored if request method is GET or HEAD.

The send(body) method must run these steps:

  • If state is not opened, throw an InvalidStateError exception.

  • If the send() flag is set, throw an InvalidStateError exception.

  • If the request method is GET or HEAD, set body to null.

This discussion in the Postman github could also help you: https://github.com/postmanlabs/postman-app-support/issues/131.

If you want to query an ElasticSearch server, you can use POST requests. Here is a sample:

POST http://localhost:9200/myindex/mytype/_search?pretty=true
Content-Type: application/json

{
  "query": {
    "match": {
      "somefield": "some value"
    }
  }
}

Hope it helps you, Thierry

like image 123
Thierry Templier Avatar answered Nov 05 '22 19:11

Thierry Templier