简体   繁体   中英

how to create an interface that will fetch info from API?

so, I wanted to create an interface that will fetch brewery information, based on a brewery/beer name. I fetch the API to my code but I don't know how to get the info from it with my button. I want it to show me at least two locations but get an error every time. I'm new to JS and so confused here, The error is: 404 page not found- when submitting the city name. this is my code:

<!DOCTYPE html>
<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
 </head>
 <body>
  <h1>The Beer Mapping</h1>

  <script>
    fetch("http://beermapping.com/webservice/locquery/API_KEY")
    .then(response=>{
      return response.json()
    }).then(data=>{
      console.log(data)
    }).then(error=>{
      console.log(error)
    }));
  </script>

  <form action="/action_page.php">
   <input type="text" name="City Name">
   <input type="submit" value="submit">
  </form>

 </body>
</html>

From the examples page of the API at https://beermapping.com/api/examples/ , it appears that the API endpoint you are attempting to use requires a parameter to be provided after the API key: http://beermapping.com/webservice/locquery/API_KEY/QUERY If you are to load that page in your browser, you will get a blank page (presumably as no valid API key provided) rather than a 404 error, so I assume once you provide your API key this should eliminate the 404 error being received.

Looking at the rest of your code I assume that the parameter needed is based off the user input from the City Name field - so this is most likely the parameter that needs passing into the query URL after the API key.

Based on the form submission URL being a PHP file, one way to pass the user input would be to use after the API Key in the URL:

fetch("http://beermapping.com/webservice/locquery/API_KEY/<?php echo $_GET['City Name']; ?>")

however it would also be possible to process this entirely client side by changing your form handling to instead fetch the URL rather than calling an endpoint on your web server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM