简体   繁体   中英

Joi function apparently does not exist

I'm trying to validate the name using a Joi function but it tells me that Joi.validate is not a function. I have looked at similar questions and their answers have not helped. schema.validate is also not a function and switching to Joi.object inside the schema const doesn't work either. What can I do to fix this?

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

app.use(express.json());

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

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

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

app.post('/api/courses', (req, res) => {
    const schema = {
        name: Joi.string().min(3).required()
    };

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

    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);
});


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

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

Any suggestions?

You need to import Joi before using it. Consider below given line of code - const Joi = require("joi") ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM