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