Search code examples
node.jsreactjsexpresspostget

How to query api based on user form input


I have a node app in which I am calling the google places api and sending that data to the frontend. In the front end I have a basic form that posts to my node server. I want to return data from api calls based on the users form input.

I'm able to post the form to the server and I see the data in the request object however I am having trouble figuring out how can I use this data to correctly query the api based on the form inputs ?

The form

 <form method="post" class="form" action="http://localhost:3005/dyno">
<fieldset class="form-fieldset ui-input __first">
  <input type="text" name="interests" id="username" tabindex="0" />
  <label for="intrests">
    <span data-text="Interests">Intrests</span>
  </label>
</fieldset>

<fieldset class="form-fieldset ui-input __second">
  <input type="text" name="location" id="email" tabindex="0" />
  <label for="location">
    <span data-text="Location">Location</span>
  </label>
</fieldset>

  <input type="submit" value="Submit" />
  </form>

The server side code that logs the data I need

app.post('/dyno', function(request, response){

console.log(request.body.interests)
console.log(request.body.gender)

response.end()

});

The API call

 _EXTERNAL_URL = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.663918,-73.8820044&radius=2500&type=gyms&keyword=fitness&key=${KEY}`;

app.get('/ruckus',(req, res) => {
request(_EXTERNAL_URL, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) 
res.send(body) 
}
});
})

How can I return data based on the radius,type and keyword parameters based on form data inputted by a user ?


Solution

  • Client-side

    • Prevent the form submit default.
    • Form the body or query with the form inputs.
    • Make fetch request to "http://localhost:3005/dyno"
    • Render the received response from that request.

    Server-side

    • You create an endpoint named '/dyno'
    • Get the body/query params from the request
    • Form the URL to make request to Google Places API
    • Make the request and return the response to client