1

My console returns: Uncaught (in promise) SyntaxError: Unexpected end of JSON input and my terminal returns: { categoryId: undefined }

This is my my routes:

router.get('/getAll', auth.verify, (req, res) => {
    const user = auth.decode(req.headers.authorization);
    const categoryId = req.params.categoryId
    UserController.getCat({ categoryId })
  .then(category => res.send(category))
})

This is my controller:

module.exports.getCat = (params) => {
    console.log(params)
    return User.findById(params.categoryId)
   .then(resultFromFindById => resultFromFindById)
}

I want to get all the data using this fetch on my component, please help me to identify whats the problem.. seems like there's nothing wrong with my syntax

useEffect(() => {
    fetch(`${process.env.NEXT_PUBLIC_API_URL}/users/getAll`, {
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
    })
    .then(res => res.json())
    .then(data => {
        if(data) {
            console.log(data)
        } 
    })
}, [])
FoxcyLoxcy
  • 81
  • 1
  • 9
  • 1
    Un-indenting your `.then` clauses is really dizzying. Are you able to use `async` functions? If so you can just `await` and deal with it. – tadman Feb 21 '21 at 01:32
  • 1
    You need to resolve the "uncaught promise" problem to find out what the actual problem is. Attach `.catch()` to the end of your promise chains, or use `await` instead. – tadman Feb 21 '21 at 01:47
  • 1
    @tadman i got it now sir, nothing wrong with my syntax.. it's just my ` .findById` is supposed to be just `.find` thanks for your effort btw :) – FoxcyLoxcy Feb 21 '21 at 01:59

1 Answers1

2

You define req.params.categoryId, and it is string by the way. So, when you execute function getCat and defined it as object, it return error.

router.get('/getAll', auth.verify, (req, res) => {
    const user = auth.decode(req.headers.authorization);
    const categoryId = req.params.categoryId // this categoryId is string
    UserController.getCat({ categoryId }) // you define it inside curly bracket and hope it treats as object, so this causes error
  .then(category => res.send(category))
})

Better way to define categoryId as object and use raw json body, it will looks like this :

router.get('/getAll', auth.verify, (req, res) => {
    const user = auth.decode(req.headers.authorization);
    // this param variable means object and use it in function getCat
    const param = {
      categoryId: req.body.categoryId
    }
    UserController.getCat(param)
  .then(category => res.send(category))
})
Mudzia Hutama
  • 414
  • 3
  • 8