troubleshooting Question

Getting errors trying to run a sample node/express example I copied from YouTube.

Avatar of Gene Klamerus
Gene KlamerusFlag for United States of America asked on
JavaScriptNode.js* Express* joi
6 Comments1 Solution11 ViewsLast Modified:
I've been building out a sample node/express example that Mosh put up on YouTube.

The issue at the moment is errors in using joi to validate a post request.

At this point the code is very small so I'm including it here.  It's just one file.

const Joi = require('joi');
const express = require('express');
const app = express();


app.use(express.json());


const courses = [
    {id: 1, name: 'course1'},
    {id: 2, name: 'course2'},
    {id: 3, name: 'course3'},
];




app.get('/', (req, res) => {
    res.send('Hello World!!!');
});


app.get('/api/courses', (req,res) => {
    // res.send([1, 2, 3]);
    res.send(courses);
});


app.get('/api/courses/:id', (req, res) => {
    //res.send(req.params.id);
    const course = courses.find(c => c.id === parseInt(req.params.id));
    if (!course)
        res.status(404).send('A course with the provided id was not found');
    res.send(course);
});




app.post('/api/courses', (req, res) => {


    const schema = {
        name:  Joi.string().min(3).required()
    };


    const result = Joi.validate(req.body, schema);


    if (result.error) {
        res.status(400).send(result.error);
        return;
    }


    const course = {
        id: courses.length + 1,
        name: req.body.name
    };
    courses.push(course);
    res.send(course);
});


const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));


The problem shows up when the code hits the Joi.validate step.  This generate the following error statement:

TypeError: Joi.validate is not a function

I'm afraid I'm completely baffled.  I'm trying to use a post from postman with the raw body content of
{
   "name": "Goo"
}

This should not generate any errors, but if the complaint is with the validate statement I think I've got an earlier syntax error or typo of some sort.



Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 6 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 6 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros