Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
Code continuing after response already sent

I am trying to write a test for sending a 404 error whenever a blog is posted without a token and I keep getting "TypeError: Cannot read properties of undefined (reading '_id')". I know this is because my user variable is null which is due to there being no token sent with the request. Shouldn't the code stop reading after the response is sent? Or is there another way to counteract this? User will only be defined when a token is sent with the request. I can sort of solve this by using if/else statements to only use code if the user var is defined but is there a more effective way? Any help would be greatly appreciated.

const blogRouter = require('express').Router();
const req = require('express/lib/request');
const Blog = require('../models/blog')
const User = require('../models/user')
const jwt = require('jsonwebtoken');
const { default: mongoose } = require('mongoose');
const { decode } = require('jsonwebtoken');
require('dotenv').config()



  blogRouter.post('/', async (request, response) => {
    console.log("Request body of blog is",request.body)
    var user = request.user
    console.log("User is", user)

    try{
      const decodedToken = jwt.verify(request.token, process.env.SECRET)
      console.log("decodedToken is", decodedToken)
    }
    catch(err){
      if(!request.token || !decodedToken.id){
        console.log("got in the catch block")
        response.status(401).json({error: "token missing or invalid"})
      }
      else {
        console.log(err)
      }
    }

    const body = request.body


    const newBlog = new Blog({
      title: body.title,
      author:body.author,
      url: body.url,
      likes: body.likes,
      user: user._id           // Error here because user is null
    })


    console.log("newBlog is",newBlog)

    if (newBlog.title == null && newBlog.url == null){
      response.status(400)
      response.end()
    }
    else{
      newBlog.save()
      user.blog = user.blog.concat(newBlog._id)
      user.save()
      .then(result => {
        console.log("Saved to database!!!!!")
        response.status(201).json(result)
      })
      .catch(error => {
        console.log("Could not save to database")
      })
    }
  })

  module.exports = blogRouter
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!