Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
714 views
in Technique[技术] by (71.8m points)

javascript - JSON-Server API request from two api's. I need to enter a postcode and return weather information

I'm using JSON-server to create a weather app.

I would like to call the provided API with a GET request to retrieve the weather data for any given postcode. I.E if user types into the search bar E8 3DB it will return the temperature, clouds and description.

The two api urls are http://localhost:3030/locations and http://localhost:3030/weather

I will post the code I have tried at the bottom but I'm not sure how to go about the nexts steps or if I'm approaching it in the right way.

Is there a away to create a query when the search string has spaces like in a postcode?

Any help is appreciated :)

JSON-server documentation

{
  "locations": [
    {
      "id": 145,
      "postcode": "E8 3DB",
      "eastings": 533638,
      "northings": 184527,
      "country": "England",
      "nhs_ha": "London",
      "longitude": -0.074253,
      "latitude": 51.543824
    },
    {
      "id": 233,
      "postcode": "M5 3AA",
      "eastings": 381457,
      "northings": 397673,
      "country": "England",
      "nhs_ha": "North West",
      "longitude": -2.280845,
      "latitude": 53.475455
    },
    {
      "id": 314,
      "postcode": "B9 4BB",
      "eastings": 408295,
      "northings": 286771,
      "country": "England",
      "nhs_ha": "West Midlands",
      "longitude": -1.879291,
      "latitude": 52.478819
    },
    {
      "id": 144,
      "postcode": "EX1 3AB",
      "eastings": 294187,
      "northings": 93121,
      "country": "England",
      "nhs_ha": "South West",
      "longitude": -3.500568,
      "latitude": 50.728041
    }
  ],
  "weather": [
    {
      "id":2643743,
      "coord": {"lon":-0.07,"lat":51.54},
      "weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],
      "base":"stations",
      "main":{"temp":289.28,"feels_like":285.24,"temp_min":288.71,"temp_max":290.15,"pressure":1016,"humidity":77},
      "visibility":10000,
      "wind":{"speed":6.7,"deg":230},
      "clouds":{"all":90},
      "dt":1604060381,
      "sys":{"type":1,"id":1414,"country":"GB","sunrise":1604040660,"sunset":1604075829},
      "timezone":0,
      "name":"London"
    },
    {
      "id":2643123,
      "coord": {"lon":-2.28,"lat":53.48},
      "weather":[{"id": 500,"main": "Rain","description": "light rain","icon": "10n"}],
      "base":"stations",
      "main":{"temp":285.76,"feels_like":284.05,"temp_min":285.15,"temp_max":285.93,"pressure":1012,"humidity":100},
      "visibility":10000,
      "wind":{"speed":3.6,"deg":270},
      "clouds":{"all":90},
      "dt":1604060843,
      "sys":{"type":1,"id":1379,"country":"GB","sunrise":1604041483,"sunset":1604076019},
      "timezone":0,
      "name":"Manchester"
    },
    {
      "id":3402721,
      "coord":{"lon":-1.88,"lat":52.48},
      "weather":[{"id": 800,"main": "Clear","description": "clear sky","icon": "01d"}],
      "base":"stations",
      "main":{"temp":302.15,"feels_like":304.15,"temp_min":302.15,"temp_max":302.15,"pressure":1014,"humidity":70},
      "visibility":10000,
      "wind":{"speed":4.6,"deg":90,"gust":11.3},
      "clouds":{"all":40},
      "dt":1604061309,
      "sys":{"type":1,"id":8426,"country":"GB","sunrise":1604044422,"sunset":1604088963},
      "timezone":0,
      "name":"Birmingham"
    },
    {
      "id":2015306,
      "coord":{"lon":-3.50,"lat":50.73},
      "weather":[{"id":602,"main":"Snow","description":"heavy snow","icon":"13d"}],
      "base":"stations",
      "main":{"temp":262.28,"feels_like":257.3,"temp_min":262.28,"temp_max":262.28,"pressure":1028,"humidity":96,"sea_level":1028,"grnd_level":1023},
      "visibility":628,
      "wind":{"speed":2.61,"deg":331},
      "clouds":{"all":100},
      "dt":1604061539,
      "sys":{"country":"GB","sunrise":1604016259,"sunset":1604038312},
      "timezone":32400,
      "name":"Exeter"
    }
  ]
}

My attempt so far ...


import React, { useEffect } from "react";
// import { isValid } from "postcode";

export default function PostcodeInputForm() {
  const [postcode, setPostcodeValue] = React.useState("");
  const [longitude, setLongitude] = React.useState("");
  const [latitude, setLatitude] = React.useState("");

  const storePostcode = (event) => {
    event.preventDefault();
    setPostcodeValue(event.target.value);
  };

// Error handling: If there isn't any response from the server return an error

  const checkResponse = (response) => {
    if (!response.ok) throw new Error(`Network error: ${response.status}`);
    return response.json();
  };

  const getLocations = () => {
    fetch("http://localhost:3030/locations")
    .then(checkResponse)
      .then((result) => {
        result.map((object) => {
          console.log(postcode);
          if (object.postcode == postcode) {
            
            setLongitude(object.longitude);
            setLatitude(object.latitude);
          }
        });
      })
  }

  useEffect(() => {
    getLocations();
  }, []);

  console.log(longitude, latitude);
  console.log(postcode);

  
  return (
    <form onSubmit={getLocations()}>
      <input
        placeholder="Enter your postcode... "
        type="text"
        className="postcode-search-bar"
        id="postcode"
        name="postcode"
        required
        value={postcode}
        onChange={storePostcode}
      />
      <button type="submit">Submit</button>
    </form>
  );
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...