Tanmay Kulkarni
Tanmay Kulkarni

Reputation: 45

I am getting RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: undefined

I am creating a note-taking app and I am getting the above error when I run the app. The error points out to this chunk of code -

app.use((err,req,res,next)=>{
    res.status(err.status).json({
        error : {
            message : err.message
        }
    });
})

This is the entire code in my app.js

// Import modules as variables

const express = require('express'); // Required for routing
const bodyParser = require("body-parser"); // Required to pass JSON data between Client Side & Server Side
const app = express(); // Create instance of express application
app.use(bodyParser.json()); // State the express application to use the body-parser module and parse JSON data through it
const path = require('path'); // Required to serve a static HTML file

const Joi = require('joi');

const schema = Joi.object().keys({
    notes : Joi.string().required()
});

const db = require("./db"); // Initialize db as required db path
const collection = "notes"; // Initialize name of the collections as "notes"

// GET Routes

// Send a static HTML file to the user

app.get('/',(req,res)=> // Root get path & pass response & request object
{
    res.sendFile(path.join(__dirname,'index.html')); // Send a static HTML file from the path module
});

// Query the database for all the notes from the notes collection and return them to the user

app.get('/getNotes',(req,res)=> // getNotes path & pass response & request object
{
    db.getDB().collection(collection).find({}).toArray((err,documents)=> // Call the getDB method (Line #51 od db.js file) & pass the name of the collection.Call the method find to have all the documents from the Notes collection.
    {
        if(err) // If there is an error, print an error in the console for the user
        {
            console.log(err);
        }
        else // If there is no error, print the documents returned form the server and get the response of the documents in JSON format
        {
            console.log(documents);
            res.json(documents);
        }
    });
});


// UPDATE Routes

// Pass a route parameter. The id is the primary key of the document needed to update. Pass the request & response function

app.put('/:id',(req,res)=>
{
    const notesID = req.params.id; // get the ID of the notes
    const userInput = req.body; // get the input of the notes from the user. User's data will be in the form of JSON

    // Connect to the database and called the notes collection. Call a function findOneAndUpdate and pass the first argument as query object hence pass find by ID & notes. Pass the document for update, Pass the options and set returnOriginal to false. Pass the call back and pass error and result

    db.getDB().collection(collection).findOneAndUpdate({_id : db.getPrimaryKey(notesID)},{$set: {notes : userInput.notes}},{returnOriginal : false},(err,result)=>
    {
       if(err) // If there is an error, print an error in the console for the user
       {
           console.log(err);
       }
       else // If there is no error then display the result as a response in JSON format
       {
           res.json(result);
       }
    });
});

// CREATE Routes

app.post('/',(req,res, next)=>
{
    const userInput = req.body;

    Joi.validate(userInput,schema,(err,result)=>{
        if(err){
            const error = new Error("Invalid Input");
            error.status = 400;
            next(error);
        }
        else {
            db.getDB().collection(collection).insertOne(userInput,(err,result)=>
            {
                if(err)
                {
                    const error = new Error("Failed to insert Note");
                    error.status = 400;
                    next(error);
                }
                else
                    res.json({result : result, document : result.ops[0], msg : "Successfully created a note",error : null});
            });
        }
    })
});



// DELETE Route

app.delete('/:id',(req,res)=>
{
   const notesID = req.params.id;

   db.getDB().collection(collection).findOneAndDelete({_id : db.getPrimaryKey(notesID)},(err,result)=>
   {
       if(err)
           {
             console.log(err);
           }
       else
       {
           res.json(result);
       }
   });
});

app.use((err,req,res,next)=>{
    res.status(err.status).json({
        error : {
            message : err.message
        }
    });
})

// Connect to the database [line #19 of db.js file]

db.connect((err)=> // Pass a callback
{
    if (err) // If there is an error in connecting to the database print "Unable to connect to database" in the console and terminate the application
    {
        console.log('Unable to connect to database');
        process.exit(1);
    }
    else // If a database connection is successful, listen on port 3000 and print "connected to database, app listening on port 3000" in the console
    {
        app.listen(3000,()=>
        {
            console.log('connected to database, app listening on port 3000')
        });
    }
})

The following is the error I am getting when I try to create a note -

enter image description here

Please find the screen-recording of the error in this Drive Link

I am not sure why this happening. Any help will be highly appreciated. Thank you!

Upvotes: 0

Views: 7154

Answers (1)

Efi Shtainer
Efi Shtainer

Reputation: 394

app.use((err,req,res,next)=>{
   // because err.status is undefined 
    res.status(404).json({
        error : {
            message : err.message
       }
    });
})

and a little more about Error: What properties does Node.js express's Error object expose?

const schema = Joi.object({
    notes: Joi.string()
    .required()})

... Validation ...
const { error, value } = schema.validate({ a: 'a string' });
// if input is vaild error will be undefined

more on the docs https://joi.dev/api/?v=17.3.0

Upvotes: 2

Related Questions