POST endpoints not working with Express - node.js

I am writing a daily daycare reporting app using the PERN stack and I am having issues with some of my POST endpoints. The one below works correctly:
app.get('/classroomList', (req, res) => {
classroom.getClassrooms().then((classrooms) => { res.send(classrooms) })
})
app.get('/classroomList/:id',(req,res)=>{
classroom.getStudentsByClass(req.params.id).then((student)=>{
res.send(student)
})
})
app.post('/classroomList', (req, res) => {
classroom.createClassroom(req.body)
.then((classroom)=>{res.send(classroom.attributes)})
})
app.delete('/classroomList/:id', (req, res) => {
console.log('req received')
classroom.deleteClassroom(req.params.id).then((classroom) => {
res.send('Deleted')
})
})
}
However I have a few others that are written in the same exact way that come back with the error:
TypeError students.createStudent is not a function
The one below does not work and throws the aforementioned error message
module.exports = (app) => {
const students = require('../controllers/studentController')
app.get('/studentList', (req, res) => {
students.getStudents().then((students) => { res.send(students) })
})
app.delete('/studentList/:id', (req, res) => {
students.deleteStudent(req.params.id).then((student) => {
res.send('Deleted')
})
})
app.post('/studentList', (req, res) => {
console.log(req.body)
students.createStudent(req.body)
.then((student)=>{console.log(student.attributes)})
})
}
This is the controller that works:
exports.createClassroom = (classroom) => {
console.log('function accessed')
const newClassroom = new Classroom(
classroom)
return newClassroom.save()
.then(classroom => {
return classroom;
})
.catch(err => {
console.log(err)
})
And this one doesn't:
exports.createStudent = (student) => {
console.log('function accessed')
const newStudent = new Student(
student)
return newStudent.save()
.then(student => {
return student;
})
.catch(err => {
console.log(err)
})
}

Related

modify query function in Sequelize

I'm learning "Sequelize".
I went through documentation and got this code somewhere else.
Model = require('../models/Salesman')
module.exports.creareSalesman = (req, res, next) => {
Model.create(req.body).then(
result => {
res.status.json({data: result})
}).catch(err => console.log(err))
}
but I want this in the below structure,
Model = require('../models/Salesman')
module.exports.creareSalesman = (req, res, next) => {
Model.create(req.body, function (result, err) {
if (err) {
console.log(err)
}
else {
res.status.json({data: result})
}
});
}
I tried this,.it didn't send the response. But inserted the data correctly to db.
How to get the response in this case.?
The Model.create method returns a Promise, and does not have a callback parameter.
So you either handle the Promise with then:
module.exports.creareSalesman = (req, res, next) => {
Model.create(req.body)
.then((result) => {
res.status.json({ data: result });
})
.catch((err) => console.log(err));
};
Or use async await:
module.exports.creareSalesman = async (req, res, next) => {
try {
const result = await Model.create(req.body);
res.status.json({ data: result });
} catch (err) {
console.log(err);
}
};

How to redirect/render to 404 if the "_id" is wrong/misspelled in /blogs/:blogId

I want to redirect users to "404.ejs" if the post id is entered wrong/mispelled in blogs/:blogId route. How can I accomplish it in below code.
app.get('/blogs/:blogid', (req, res) => {
const requestedId = req.params.blogid;
Blog.findById(requestedId, (err, addedblogpost) => {
if (err) {
console.log(err);
}
else {
res.render("post", {
title: addedblogpost.blogTitle,
content: addedblogpost.blogContent
})
}
})
}
Code for "404"
app.get('*', (req, res) => {
res.render('404');
})
You should make use of express next parameter to get the result you want.
This will call the next "matching" middleware for the current route, assuming this would be your error handler middleware of course.
It should be used as shown below :
app.get('/blogs/:blogid', (req, res, next) => {
const requestedId = req.params.blogid;
Blog.findById(requestedId, (err, addedblogpost) => {
if (err) {
next();
}
else {
res.render("post", {
title: addedblogpost.blogTitle,
content: addedblogpost.blogContent
})
}
})
Express doc : https://expressjs.com/en/guide/using-middleware.html
app.get('/blogs/:blogid', async (req, res) => {
const requestedId = req.params.blogid;
const blog = await Blog.findById(requestedId);
if (!blog) return res.render("404");
res.render("post");
}
to check if the blog is null or not.

How to pass variable to get request

I've got this function that calls a get request:
confirmUser(username: string) {
this.http.get<{ users: User[] }>('http://localhost:3000/users').subscribe(
// success function
(response) => {
this.user = response.users;
console.log(this.user);
}
),
(error: any) => {
console.log(error);
}
}
How can I make it so that the username being passed in in the above function be available to replace the username Grok here:
router.get('/', (req, res, next) => {
// User.find().then(users => {
User.findOne({username: "Grok"}, {} ).then(users => {
res.status(200).json({
users: users
});
})
.catch(error => {
returnError(res, error);
});
});
The value of username is coming from a form field, so the component calling this is not subscribed to any URL parameters, if that makes a difference.
if you pass it as a parameter you should use req.params, otherwise req.query for querystring.
using param (i.e.: http://localhost:3000/users/grok):
router.get('/:username', (req, res, next) => {
// User.find().then(users => {
User.findOne({username: req.params.username }, {} ).then(users => {
res.status(200).json({
users: users
});
})
.catch(error => {
returnError(res, error);
});
});
using querystring (i.e.: http://localhost:3000/users?username=grok) :
router.get('/', (req, res, next) => {
// User.find().then(users => {
User.findOne({username: req.query.username }, {} ).then(users => {
res.status(200).json({
users: users
});
})
.catch(error => {
returnError(res, error);
});
});

Subscribe method does not work in angular

product-operations.component.ts
deleteProduct() {
this.productsService.delete_product(this.deleteID).subscribe((res: any) => {
console.log("helloooooo");
});
};
product.service.ts
delete_product(id) {
return this.http.delete("http://localhost:3000/delete_product/" + id);
}
backend
exports.deleteProduct = (req, res, next) => {
const id = req.param("id");
Product.deleteOne({ _id: id })
.then(() => {
console.log("deleted");
})
.catch(err => {
console.log(err);
});
};
Problem:
In the above codes, the deleteProduct function in product-operations.component.ts doesn't work properly. More precisely, it does the removal. But after doing the uninstall, subscribe doesn't run its contents. This prevents my instant update after deletion. How can I solve this?
Try to send a response back from the server.
exports.deleteProduct = (req, res, next) => {
const id = req.param("id");
Product.deleteOne({ _id: id })
.then(() => {
res.send({}) // or res.send({id: id})
console.log("deleted");
})
.catch(err => {
res.status(500)
res.send({error: err})
console.log(err);
});
};

Node/Express Route 'Show' presenting too many results

This is for the backend of a MEAN site.
I am currently trying to create several search functions based off of different params in the same mongoose model. For the Controller I have
show:(req,res) => {
Activity.findById
({_id: req.params._id}).then(activity => {
res.json(activity)
})
.then(console.log(req.query._id))
},
show: async (req, res, next) => {
const linkClicked = await Activity.find
({linkClicked: req.params.linkClicked})
.then(result => {
res.send(result)
})
.then(next())
.catch(err => (console.log(err)))
},
show:(req,res, next) => {
Activity.find({caseAssigned: req.params.caseAssigned}).then(action => {
res.json(action)
next()
})
.catch(err => (console.log(err)))
},
show:(req,res, next) => {
Activity.find({addedToQue: req.params.addedToQue}).then(activity => {
res.json(activity)
next()
})
.catch(err =>(console.log(err)))
},
show:(req, res, next) => {
Activity.find({statusChanged: req.params.statusChanged}).then(activity => {
res.json(activity)
next()
})
.catch(err => (console.log(err)))
},
show:(req,res) => {
Activity.findById
({_id: req.params._id}).then(activity => {
res.json(activity)
})
.then(console.log(req.query._id))
},
show: async (req, res, next) => {
const linkClicked = await Activity.find
({linkClicked: req.params.linkClicked})
.then(result => {
res.send(result)
})
.then(next())
.catch(err => (console.log(err)))
},
show:(req,res, next) => {
Activity.find({caseAssigned: req.params.caseAssigned}).then(action => {
res.json(action)
next()
})
.catch(err => (console.log(err)))
},
show:(req,res, next) => {
Activity.find({addedToQue: req.params.addedToQue}).then(activity => {
res.json(activity)
next()
})
.catch(err =>(console.log(err)))
},
show:(req, res, next) => {
Activity.find({statusChanged: req.params.statusChanged}).then(activity => {
res.json(activity)
next()
})
.catch(err => (console.log(err)))
},
For the routes I have:
const express = require('express');
const controllerRouter = express.Router();
const activityController = require("../controllers/activity")
controllerRouter.get("/", activityController.index)
// controllerRouter.get("/search/:_id", activityController.show)
controllerRouter.get("/event/:linkClicked/linkClicked/", activityController.show)
controllerRouter.get("/event/caseAssigned/:caseAssigned", activityController.show)
controllerRouter.get("/event/addedToQue/:addedToQue", activityController.show)
controllerRouter.get("/event/statusChanged/:statusChanged", activityController.show)
When I search in postman for /event/true/linkClicked I receive JSON that does not have linkClicked:true.
Solutions I have tried:
1) I tried implementing the next() function in my controller and adding async capability. I'm not sure if I implemented this correctly. I've made sure that my JSON data is accurate.
Any help is appreciated. (Also, this is my first post so if I have left out a necessary detail, please, let me know.)

Resources