Section 8: Accessing API from Browser (Weather App)
Now, we want to be able to build an application where the user can enter something in the browser, and we retrieve the data for that input.
The Query String
As you know, we can pass query strings into browser addresses, such as:
The key value pairs after the ? represent the query string. It is always a key value pair. This query can be used by express, such as the following:
Now, we say we have built a weather page. Naturally, we would need the address of some place to fetch the weather. So, we can build these requirements into the code:
Building a JSON HTTP Endpoint
Now, we can connect the above app.get with HTTP requests made in the earlier module. Effectively, we can now take create a something, where user enters a form, which enters the needed address into the query, and now, we can access API and retrieve the data and send it back to the client.
(We take a short break and introduce a new JavaScript feature, default function parameters)
Really, its just the same thing as what we would expect from C++.
As seen above, we can even define default values for an object.
Browser HTTP Requests with Fetch
Fetch is something we would use in our client-side javascript files. This file is not interacting on Nodejs. So, fetch is not something files that will be run on the Node server can understand. This is used in the JavaScript file that will be used as a source for the html page. if you recall, you probably have seen this being used in some React tutorials. The syntax would be like so:
Now, with this, we can finally have a form on the web page, have it submitted, and have its contents used to fetch data, by using the express request methods we have defined, and then finally accessing the API data, returning it, and rendering it to the screen. The above βresponseβ is precisely what we .send from the app.get. Here is the full client-side JavaScript code: