Aman Gupta
Aman Gupta

Reputation: 3797

HTTP POST v/s HTTP GET

I want to make a database query from frontend (Angular) to backend. But I need to send lots of parameters for that.

As far as I understand, if we are not making any database changes, it is better to use GET as it uses cached entries. POST should be used used if we need to make changes on server/DB.

But if I want to send many parameters (some are serialized objects) and make no server side changes, will it be alright to use POST request in that case and embed all parameters in the POST body instead of sending a huge URL encoded GET request?

Upvotes: 1

Views: 817

Answers (2)

Sk. Tajbir
Sk. Tajbir

Reputation: 290

I think you should use POST in this situation which is more manageable and looks clean. For more benefit of post follow these links:

Upvotes: 0

CodeCaster
CodeCaster

Reputation: 151586

To first clear this up: responses to POST requests can be cached, as long as the origin server returns the proper caching response headers. However, browsers and proxy servers generally don't apply caching to POST requests.

That being said, with the proper encoding you can store a lot of information in the ~ 2 KB of a query string, so GET should be the way to go.

If you're certain you'll go beyond the limits of a GET request and you'll need to go the POST way while remaining cacheable, you could introduce a kind of "nonce", for example using a hash of the search parameters:

  1. Client does a POST to /search, with the search parameters.
  2. Server stores the parameters somewhere, for example in a database.
  3. Server generates a nonce from the parameters, for example by hashing the search parameters, or the row ID.
  4. Server redirects the client to the result page for that nonce: /search/123abc.
  5. Client requests the /search/123abc search results page.
  6. Server performs the search based on the nonce, and returns a response which is cacheable.

This will introduce one additional HTTP roundtrip, but enable caching cross-browser and through proxy servers.

Upvotes: 1

Related Questions