简体   繁体   中英

Can't seem to fetch data from SeatGeek API

So I'm trying to retrieve data when a user inputs a performer's name with the SeatGeek API. At the moment, I'm simply typing in the query string in my URL to make sure my Key is working. So this:

https://api.seatgeek.com/2/events?performers.slug=new-york-mets&client_id=MY_CLIENT_ID

Works, and I can get a JSON with information about New York Mets events.

Example:

  "meta": {
    "total": 192,
    "per_page": 10,
    "page": 1,
    "took": 2,
    "geolocation": null
  },
  "events": [ARRAY OF EVENTS]

Server side and fetching data:

Inside my form I'm making a POST request to /events :

app.post('/events', function(req, res) {
  let band = req.body.bandName;
  band = band.split(' ').join('-')

  fetch(`https://api.seatgeek.com/2/events?performers.slug=${band}&client_id=MY_CLIENT_ID`)
    .then(function(data){
      res.json(data);
    }).catch(function(error){
      console.log(error);
    });
});

When I hit the POST request, I get different data. I'm not even entirely sure what this is:

{
  "url": "https://api.seatgeek.com/2/events?performers.slug=new-york-mets&client_id=OTk1Mzg2MXwxNTEzMTkwMDUyLjI3",
  "status": 200,
  "statusText": "OK",
  "headers": {
...
 "body": {
"_readableState": {
  "objectMode": false,
  "highWaterMark": 16384,
  "buffer": {
    "head": null,
    "tail": null,
    "length": 0
  }, etc...

Am I doing the fetch request wrong?

That's the Response object you get back from fetch in the then .

The idea is that Response is a stream of data, and to actually access the data you get back from an API, you need to read the Response stream to completion.

To access the actual fetched JSON, you'll need to access Body.json , a method available to responses because they implement the Body interface:

fetch(`https://api.seatgeek.com/2/events?performers.slug=${band}&client_id=MY_CLIENT_ID`)
  .then(function(response) {
    return response.json();
  }).then(function(json) {
    res.json(json);
  }).catch(function(error) {
    console.log(error);
  });

Notice the new then . response.json() reads the Response stream to completion and actually returns a promise that resolves with the JSON when the stream is exhausted. The first then waits for the JSON, and after, sends the fetched JSON from SeatGeek to your own API's user in the second then .

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