Search code examples
javascriptpromisefetch

When using the Fetch API, why do post requests require more inputs than a get request?


How come when we use the Fetch API, it requires a significant amount of more input into the function for a POST request as opposed to a GET request. This has been a bit of a learning curve for myself. Also, what determines the headers you need to use for a POST request?


Solution

  • TLDR, POST has more stuff to it.

    GET and POST are methods for HTTP Requests. The main ones of interest are:

    • GET: get a thing
    • POST: make a new thing
    • PUT: change a thing
    • DELETE: delete a thing

    The most basic form of a GET is asking a specific URI to send back pre-set data. Also, GET tends to be the most common use request so most HTTP request-making methods will make this very simple. Thus, GET is often done with little more than a URI.

    In contrast, POST has a lot going on.

    1. You aren't making a GET request. This is more specific to Fetch API as it assumes GET by default so you need to specify in the options that you are using method: "POST".
    2. You are, by definition, sending data. Therefore, you must include that data in the method: body: myData
    3. Data has a format. The server has no idea if you sent it a string, and integer, a JSON, or the whole Harry Potter movie set. It just sees a stream of 1s and 0s. This is where headers come in, which let you specify to the server that you are sending it a JSON object or an image file so that the server can appropriately deal with the bits. Thus, we see headers: { 'Content-Type': <MIME type of myData> } in the options.