Home > Software engineering >  express path issues when using same logic on diffrent paths
express path issues when using same logic on diffrent paths

Time:06-02

id path is working (I get the result from the json), but even though pokeName uses the same logic, I dont get any data from it. What have we missed?

JSON: https://github.com/Biuni/PokemonGO-Pokedex/blob/master/pokedex.json

const Pokemons = mongoose.model('Pokemons', {
  id: Number,
  name: String,
  type: Array,
})
_____

app.get('/pokemons', async (req, res) => {
  try {
    if (!allPokemons) {
      res.status(404).send('No data to show')
    } else {
      res.json(allPokemons.pokemon) /*[1].name*/
    }
  } catch (error) {
    res.status(400).json({ error: 'Not found' })
  }
})

_____

app.get('/pokemons/id/:id', async (req, res) => {
  const { id } = req.params
  const pokemon = allPokemons.pokemon.find((item) => item.id ===  id)
  try {
    if (!pokemon) {
      res.status(404).send('No pokemon found with this ID')
    } else {
      res.json(pokemon)
    }
  } catch (error) {
    res.status(400).json({ error: 'Not found' })
  }
})

_____ 

app.get('/pokemons/name/:pokeName', async (req, res) => {
  const { pokeName } = req.params
  const pokemon = allPokemons.pokemon.find((item) => item.name ===  pokeName)
  try {
    if (!pokemon) {
      res.status(404).send('No pokemon found with this name')
    } else {
      res.json(pokemon)
    }
  } catch (error) {
    res.status(400).json({ error: 'Not found' })
  }
})

CodePudding user response:

You're trying to convert the name to a number (presumably because id is a number, and you copied its code):

item.name ===  pokeName

But it's not, so this will result in a NaN. Remove the :

item.name === pokeName
  • Related