Review for my API, I'm a beginner please help!

In the code below

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

app.use(express.json());

const courses = [
    { id: 1, name: 'bca' },
    { id: 2, name: 'bba' },
    { id: 3, name: 'mba' },
];

// GET WORING

app.get('/', (req,res) => {
    res.send('hello works');
});

app.get('/api/courses', (req,res) => {
    res.send(courses);
});

app.get('/api/courses/:id', (req,res) => {
    const course = courses.find(c=> c.id === parseInt(req.params.id));
    if(!course) return res.status(404).send('The Course with given id not found');
    else res.send(course);
});

// POST

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

    const { error } =  validateCourse(req.body); // result.error
    if(error) return res.status(400).send(result.error.details[0].message);

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


// PUT

app.put('/api/courses/:id', (req,res) => {
    
    // LOOK UP THE COURSE
    const course = courses.find(c=> c.id === parseInt(req.params.id));
    if(!course) return res.status(404).send('The Course with given id not found');

    // const result =  validateCourse(req.body); or 
    const { error } =  validateCourse(req.body); // result.error
    if(error) return res.status(400).send(result.error.details[0].message);
    
    // UPDATE COURSE
    course.name = req.body.name;
    // RETURN TO CLIENT
    res.send(course);
});


// DELETE

app.delete('/api/courses/:id', (req,res)=>{
    // LOOK UP THE COURSE
    const course = courses.find(c=> c.id === parseInt(req.params.id));
    if(!course) return res.status(404).send('The Course with given id not found');  

    const index = courses.indexOf(course);
    courses.splice(index, 1);

    res.send(course);
})


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

    return Joi.validate(req.course, schema);
}

// PORT
const port = process.env.PORT || 8000; //PROCESS IS OBJECT
app.listen(port, () => console.log(`Listening on port ${port}`));

I have this error in POST and PUT

ReferenceError: req is not defined
    at validateCourse (/home/alex/Documents/learning_node/express_1/index.js:83:25)
    at app.post (/home/alex/Documents/learning_node/express_1/index.js:33:24)
    at Layer.handle [as handle_request] (/home/alex/Documents/learning_node/express_1/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/alex/Documents/learning_node/express_1/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/alex/Documents/learning_node/express_1/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/alex/Documents/learning_node/express_1/node_modules/express/lib/router/layer.js:95:5)
    at /home/alex/Documents/learning_node/express_1/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/home/alex/Documents/learning_node/express_1/node_modules/express/lib/router/index.js:335:12)
    at next (/home/alex/Documents/learning_node/express_1/node_modules/express/lib/router/index.js:275:10)
    at jsonParser (/home/alex/Documents/learning_node/express_1/node_modules/body-parser/lib/types/json.js:119:7)

Read the stack trace, it’s telling you the issue – this function:

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

    return Joi.validate(req.course, schema);
}

This line:

return Joi.validate(req.course, schema);

req is not passed into that function anywhere, so you need to pass it in to be able to use req.course

Okay thanks I will try to fix it

@DanCouper

I fixed the code

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

app.use(express.json());

const courses = [
    { id: 1, name: 'bca' },
    { id: 2, name: 'bba' },
    { id: 3, name: 'mba' },
];

// GET WORING

app.get('/', (req,res) => {
    res.send('hello works');
});

app.get('/api/courses', (req,res) => {
    res.send(courses);
});

app.get('/api/courses/:id', (req,res) => {
    const course = courses.find(c=> c.id === parseInt(req.params.id));
    if(!course) return res.status(404).send('The Course with given id not found');
    else res.send(course);
});

// POST

app.post('/api/courses', (req,res) => {
    const { error } =  validateCourse(req.body); // result.error
    if (error) return res.status(400).send(error.details[0].message);

    const course = {
        id: courses.length + 1,
        name: req.body.name
    };

    courses.push(course);
    res.send(course);
});


// PUT

app.put('/api/courses/:id', (req,res) => {
    const course = courses.find(c => c.id === parseInt(req.params.id));
    if(!course) return res.status(404).send('The Course with given id not found');
    
    const { error } =  validateCourse(req.body); // result.error
    if(error) return res.status(400).send(error.details[0].message);
    
    course.name = req.body.name;    // UPDATE COURSE
    res.send(course);               // RETURN TO CLIENT
});


// DELETE

app.delete('/api/courses/:id', (req,res)=>{
    // LOOK UP THE COURSE
    const course = courses.find(c=> c.id === parseInt(req.params.id));
    if(!course) return res.status(404).send('The Course with given id not found');  

    const index = courses.indexOf(course);
    courses.splice(index, 1);

    res.send(course);
});


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

    return Joi.validate(course, schema);
}

// PORT
const port = process.env.PORT || 8000; //PROCESS IS OBJECT
app.listen(port, () => console.log(`Listening on port ${port}`));

BUT NOW I HAVE THIS ERROR
When i make POST

Remember, JSON objects require key and values pairs to be in double quotes.
{ "name": "new course" }

@austinlords
It’s still showing that same response that
"name" is required

is there some problem with code ?

I remove the validation and then used req.body inside POST just to see what is being sent to the API and it showed this

{
    "id": 4,
    "name": {}
}

Your code looks correct to me. I’m not sure what could be causing this error if your POST request is like this:

{ "name": "new course" }

app.use(express.json()) should be parsing the body of the POST request and set req.body to the JSON object in the POST. Looks like you used that correctly to me.

I ran your code and it worked absolutely fine in my terminal…

1 Like

I Keep getting the same error.
If u have solved it please tell me how to solve this issue