Home > Software engineering >  When getting variable from router it returns requestProvider.js.map in node.js
When getting variable from router it returns requestProvider.js.map in node.js

Time:04-25

I have a node.js app. When the webpage is rendered the first time all works as expected, but when inspecting the app crashes, and the req.params.slug shows as requestProvider.js.map.

router.get('/:slug', async (req, res) => {
  const article = await Article.findOne({ slug: req.params.slug })
  if (article == null){
    res.render('/')
  } 
  res.render('articles/show', { article: article })
})

Edit With Console.Log Messages

router.get('/:slug', async (req, res) => {
  console.log("slug")
  console.log(req.params)
  const article = await Article.findOne({ slug: req.params.slug })
  console.log("article")
  console.log(article)
  if (article == null){
    res.render('/')
  } 
  console.log("article")
  console.log(article)
  console.log("title")
  console.log(article.title)
  res.render('articles/show', { article: article })
})

The console messages are

slug { slug: 'requestProvider.js.map' } article null article null title C:\Users\samue\OneDrive\Desktop\shortcuts and unused\Unused 2\Blog\public\routes\articles.js:32 console.log(article.title) ^

TypeError: Cannot read properties of null (reading 'title') at C:\Users\samue\OneDrive\Desktop\shortcuts and unused\Unused 2\Blog\public\routes\articles.js:32:23 at processTicksAndRejections (node:internal/process/task_queues:96:5) [nodemon] app crashed - waiting for file changes before starting...

CodePudding user response:

The problem you're facing is that your null check for article doesn't actually end the function process, so later on when you call article.title it throws undefined. You can fix this by adding return infront of the response.

if (article == null) return res.render('/') 

or using optional chaining

console.log(article?.title)

overall you should try a refactor of the endpoint, I'd suggest:

router.get('/:slug', async (req, res) => {

  const { slug } = req.params        // destructure slug from params
  if (!slug) return res.render('/')  // check if provided

  try {
    const article = await Article.findOne({ slug })
    return res.render('articles/show', { article })
  } catch(err) {
    res.status(400) // or some other error repsonse
    return res.render('your error page')
  }
})

note: This is untested

  • Related