maii
maii

Reputation: 49

get route is correct but api is still not working(fetching nothing)

I am trying to make a get route for this API:

https://api.nasa.gov/mars-photos/api/v1/rovers/opportunity/photos?sol=1000&api_key=92Ll6nGuQhfGjZnT2gxaUgiBhlCJ9K1zi2Fv5ONn

And although the syntax for the get route, the API still doesn't work in postman nor in client-side.

Here's the get route code:

app.get('/roverInfo/:rover_name', async (req, res) => {
  const { rover_name } = req.params

  try {
    let images = await fetch(`https://api.nasa.gov/mars-photos/api/v1/rovers/${rover_name}/photos?sol=1000&api_key=${process.env.API_KEY}`).then((res) => res.json())
    res.send({ images })
  } catch (err) {
    console.log('error:', err)
  }
})

sandbox here

and here's the client-side request:

const showRovers = async (rovers) => {
  try {
    await fetch(`https://localhost:3000/roverInfo/:rover_name`)
      .then((res) => {
        return res.json()
      })
      .then((rovers) => updateStore(store, { rovers }), console.log(rovers))
  } catch (error) {
    console.log('errors:', error)
  }
}

and here's the error I am getting:

Failed to load resource: net::ERR_SSL_PROTOCOL_ERROR

Upvotes: 0

Views: 123

Answers (1)

Mic Fung
Mic Fung

Reputation: 5692

ADVISE: Don't mix await/async with .then, use either one

app.get("/roverInfo/:rover_name", async (req, res) => {
  const { rover_name } = req.params;

  try {
    const res = await fetch(
      `https://api.nasa.gov/mars-photos/api/v1/rovers/${rover_name}/photos?sol=1000&api_key=${process.env.API_KEY}`
    ) // removed .then
    const images = await res.json(); // await response to json
    res.send({ images });
  } catch (err) {
    console.log("error:", err);
  }
});

02. should be http instead of https

03. need to pass rover name to param instead of using :rover_name

let getRovers = showRovers('opportunity');

const showRovers = async (roverName) => {
  try {
    console.log("roverName", roverName)
    // use http here
    await fetch(`http://localhost:3000/roverInfo/${roverName}`) 
      .then((res) => {
        return res.json();
      })
      .then((rovers) => updateStore(store, { rovers }));
  } catch (error) {
    console.log("errors:", error);
  }
};

Upvotes: 1

Related Questions