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");
Related
I am creating a post request that adds new posts to MongoDB. The post request works well and I can see the post in Mongo.
I am struggling at accessing properties from the object using req.body, specifically req.body._id. I would like to console.log the req.body._id to verify that it worked. In the terminal, I keep on getting 'undefined'.
All the solutions I have seen so far say include app.use(express.json()); and app.use(express.urlencoded({ extended: false })); which I have.
I am stumped on what to try next. Any suggestions would be appreciated.
Here is my server.js file
const express = require('express');
const dotenv = require("dotenv").config();
const mongoose = require('./db/mongoose');
const app = express();
const postsRoute = require('./routes/posts');
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use("/posts", postsRoute);
app.listen( process.env.PORT || 5000, (err) => {
console.log(`listening on port ${process.env.PORT}`);
});
Here is my routes file
const express = require('express');
const router = express.Router();
const { allPosts, createPost } = require('../db/models/postModel');
router.get("/", async (req, res) => {
console.log(`req.title is: ${req.title}`);
try {
const posts = await allPosts();
res.send(posts);
} catch (err) {
console.log(err.message);
}
});
router.post("/create", async (req, res) => {
const newPost = req.body;
try {
const addingPost = await createPost(newPost);
console.log(`req.body is:${addingPost}`);
console.log(`req.body title:${addingPost.title}`);
console.log(`addingPost is: ${addingPost} with id of ${addingPost._id}`);
res.send (addingPost);
} catch (err) {
res.status(500).send(err.message);
}
});
module.exports = router;
Here is my Schema file
const mongoose = require('mongoose');
const { Schema } = mongoose;
const postSchema = new Schema({
author: {
type: String,
required: true
},
title: {
type: String,
required: true
},
content: {
type: String,
required: true,
},
tags: [String],
file: String,
likes: {
type: Number,
//We want to default to 0 likes
default: 0,
},
createdAt: {
type: Date,
default: new Date(),
},
});
const postModel = mongoose.model('Post', postSchema);
//Get all posts
const allPosts = async () => {
const posts = await postModel.find();
return posts;
};
//Create posts
const createPost = async (post) => {
const newPost = await postModel.create(post);
return newPost;
};
module.exports = { allPosts, createPost };
Console.log outputs in the Node REPL
I have included a picture showing what the console.log ouputs in the terminal. Hopefully this supports my question.
I am getting an error of TypeError: Cannot read property 'message' of undefined<br> on a Postman post request for a express server code.
Server.js
const express = require('express');
const {v4: uuidv4} = require('uuid');
const app = express();
// Middleware for data on post request
app.use(express.json({extended: false}));
// Data
const todos = [
{
message: "Buy tea",
id: 1
},
{
message: "Buy wrp for lunch",
id: 2
},
{
message: "Play game",
id: 3
}
];
/* --------- API ---------- */
app.get("/", (req, res) => {
res.status(200).json(todos);
})
app.post("/", (req, res) => {
const newtodo = {
message: res.body.message,
id: uuidv4()
}
todos.push(newtodo);
res.status(201).json(todos);
})
const PORT = process.env.PORT || 5001;
app.listen(PORT, () => {
console.log(`Server running on port: ${PORT}`);
} );
On Headers I have Key Content-type Value application/json. But I keep getting the error. The screenshot is down below:
Can't seem to pinpoint the issue. Message is defined on my server.js file.
I think here should be req.body.message instead res.body.message
app.post("/", (req, res) => {
const newtodo = {
message: req.body.message,
id: uuidv4()
}
todos.push(newtodo);
res.status(201).json(todos);
})
If I'm wrong you can use optional chaining like this res?.body?.message.
Javascript Optional Chaining
I keep getting this error message whenever i try to populate my "product" page from MongoDB.
I have added the body-parser dependency.
N.B
I stored the product images in my Public folder and i am storing the imagePath in MongoDB.
Here's a snippet of my code
From my App.js
const express = require('express');
const ejs = require('ejs');
const mongoose = require('mongoose');
const bodyparser = require('body-parser');
const Product = require('./models/products');
From my product Model...
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const productSchema = new Schema({
path: {
type: String,
required: true
},
title: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
},
{timestamps : true});
const Product = mongoose.model('Product', productSchema);
module.exports = Product;
Also from my App.js files
app.get('/product/create', (req, res) => {
res.render('upload', { title: 'Add Products'});
});
app.post('/', (req, res) => {
console.log(req.body);
})
//Looping through all products
app.get('/product', (req, res) => {
Product.find().sort({ createdAt: -1})
.then((result) => {
res.render('product', { title: 'All Products', products : result})
})
.catch((err) => {
console.log(err);
})
});
//POST request to product route
app.post('/product', (req, res) => {
const product = new Product(req.body);
product.save()
.then((result) => {
res.redirect('/product');
})
.catch(err => console.log(err));
});
I have a problem with my controller when I'm writing console.log(req); I have all the content of the request body but when I write console.log(req.body); is undefined. I'm trying to write my Portfolio with Next.js React and Express.
This is my server index.js:
const express = require('express');
const next = require('next');
const routes = require('../routes');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
// SERVICE
const authService = require('./services/auth');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = routes.getRequestHandler(app);
const config = require('./config');
const portfolioRoutes = require('./routes/portfolio');
const secretData = [
{ id: '1',
title: 'Secret Data',
description: 'plans for build something !'
},
{
id: '2',
title: 'Secret Data2',
description: 'plans for build something2 !'
}
]
//MONGODB
mongoose.connect(config.DB_URI, {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => {
console.log("Db connected");
}).catch(err => console.log(err));
app.prepare()
.then(() => {
const server = express();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
var jsonParser = bodyParser.json()
server.use('/api/v1/portfolio', portfolioRoutes);
server.get('/api/v1/secret', authService.checkJWT, (req,res) => {
return res.json(secretData);
})
server.get('/api/v1/ownersite', authService.checkJWT, authService.checkRole('siteOwner'),
(req,res) => {
return res.json(secretData);
})
server.get('*', jsonParser,(req,res) => {
return handle(req,res);
})
server.use(function (err, req, res, next){
if (err.name === 'UnauthorizedError') {
res.status(401).send({title: `Invalid token...`});
}
});
server.use(handle).listen(3000, (err) => {
if(err) throw err
console.log('> Ready on http://localhost:3000');
})
}).catch((ex) => {
console.error(ex.stack)
process.exit(1);
})
This is my routes :
const express = require('express');
const router = express.Router();
const portfolioCtrl = require('../controllers/portfolio');
const authService = require('../services/auth');
router.route('').get(authService.checkJWT, authService.checkRole('siteOwner'),
portfolioCtrl.getPortfolio);
router.route('').post(authService.checkJWT, authService.checkRole('siteOwner'),
portfolioCtrl.savePortfolio);
router.route('/:id').patch(authService.checkJWT, authService.checkRole('siteOwner'),
portfolioCtrl.updatePortfolio);
router.route('/:id').delete(authService.checkJWT, authService.checkRole('siteOwner'),
portfolioCtrl.deletePortfolio);
module.exports = router;
This is my Controller:
savePortfolio: (res, req) => {
console.log(req);
const portfolioData = req.body;
const portfolio = new Portfolio(portfolioData);
portfolio.save((err, createdPortfolio) => {
if(err) {
return res.status(422).send(err);
}
return res.json(createdPortfolio);
})
},
Express route's callback function takes the parameters in the following order:
(req, res, next) =>{...}
req, the request object.
res, the response object.
next, indicating the next middleware function (Optional)
savePortfolio: (res, req) => {...} has the order wrong. That is why req.body would be undefined.
Correction: savePortfolio: (req, res) => {...}
I have coded a simple app to learn Nodejs but when i run "nodemon index.js" in cmd i have this error
TypeError: Cannot read property 'push' of undefined
app crashed - waiting for file changes before starting...
i have follow all instruction in the udemy course for learn nodejs
and i faced this problem when i separated the file into two files index.js and genres.js
genres.js
const express = require('express');
const router = express.Router;
//simple data
const genres = [{
id: 1,
name: 'course1'
},
{
id: 2,
name: 'course2'
},
{
id: 3,
name: 'course3'
}
];
//////////////////////////////////////////////////////////////////////
/////////////////////////////////// Get //////////////////////////////
//////////////////////////////////////////////////////////////////////
router.get('/', (req, res) => {
res.send(genres);
});
router.get('/:id', (req, res) => {
const genre = genres.find(c => c.id ===
parseInt(req.params.id)); //req.params.id return string
if (!genre)
return res.status(404).send('The course is not found...');
res.send(genre);
res.send(req.params.id);
});
router.get('/:year/:month', (req, res) => {
res.send(req.params);
});
router.post('/', (req, res) => {
const {
error
} = validategenre(req.body);
if (error)
return res.status(400).send(error.details[0].message);
const genre = {
id: genres.length + 1,
name: req.body.name
}
genres.push(genre);
res.send(genre);
});
router.put('/:id', (req, res) => {
const genre = genres.find(c => c.id === parseInt(req.params.id));
if (!genre)
return res.status(404).send('The course does not exist !!! ');
const result = validategenre(req.body);
if (result.error)
return res.status(400).send(result.error.details[0].message);
genre.name = req.body.name;
res.send(genre);
});
function validategenre(genre) {
const schema = {
name: Joi.string().min(3).required()
};
return Joi.validate(genre, schema);
}
module.exports = router;
index.js
const Joi = require('joi');
const genres = require('./routes/genres');
const express = require('express');
const app = express();
app.use(express.json());
app.use('/api/genres', genres);
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listining on port ${port}...`));
In genres.js, you should import
const router = express.Router();
instead of
const router = express.Router;
Also, the error you mention could be from any push in your code (without any more info), please specify the stacktrace next time :)
Use const router = express.Router() instead of const router = express.Router.
It can be wrong variable name :)
I made a mistake due to intelligence in my quick sample -
Typically signature of a ReST call is
router.get("/something", (req: any, res: any, next: any) => {
response.write("test");
response.end();
});
Here if you will notice I was using response where as i was suppose to use res
Moreover ensure you have registered your routes using
app.use(router);