Angular2 http GET with Body?

2019-06-24 19:08发布

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?

标签: get angular
3条回答
Juvenile、少年°
2楼-- · 2019-06-24 20:03

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

查看更多
叼着烟拽天下
3楼-- · 2019-06-24 20:03

You might be able to override this by using the generic request method on Http

this.http.request(SearchEndpoint, new RequestOptions({
    method: RequestMethod.Get,
    body: q.BuildPayload()
})).subscribe(...);
查看更多
别忘想泡老子
4楼-- · 2019-06-24 20:07

FWIW, I would be interested in hearing why this is desirable in https://github.com/whatwg/fetch/issues/83. For now there's no browser-based API that supports this, but we could offer it as a feature in fetch() given a convincing enough argument (and implementer interest).

查看更多
登录 后发表回答