Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to fetch countries and cities from my front end, but I know first, I need to make a server-side script on the backend to be able to do so.

If geography is a mock package where I can do so, and this is the code I have thus far, how could I prepare my backend to receive these fetch requests?

app.get('/:locations', function (req, res) {
  Geography.init().then(function() {
    console.log(Geography)
    Geography.open(req.params.url).then(function(site) {
        console.log(Geography)
         site.analyze().then(function(results) {
            res.json(results)
      })
    })
  })
})

Would it look something like this? (incomplete, of course....)

select
    countries
    cities
question from:https://stackoverflow.com/questions/65645476/creating-a-server-side-script-to-fetch-from

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

1 Answer

Taking the library I used as an example in the comments:

In the example provided in the readme, a JSON reponse is returned of an array of cities matching the filter (or close to it) such as [{}, {}, {}, ...]

So, if you wanted to form a response from this, you could just take some of the data. For example, if you wanted to return the country along with a latitude and longitude you could do:

// let "cities" be the JSON response from the library
// cities[0] is the first object in the array from the response
res.json({
    "country": cities[0].country,
    "location": {
        "lat": cities[0].loc[1], //longitude comes first
        "lon": cities[0].loc[0]
    }
});

You could implement this with your GET endpoint like:

app.get('/:locations', function (req, res) {
    cities = citiesLibrary.filter(city => city.name.match(req.params.locations));
});

But if you wanted to return all the results returned by the library then you could simply just use:

res.json(cities);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...