Subscribe method does not work in angular - node.js

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

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

Axios.get is not returning anything in nodeJS,Express

I have a problem with .get request.
Somehow it is not returning anything? (GET http://localhost:8080/admin net::ERR_EMPTY_RESPONSE)
Any suggestions?
Get Route,With this I'm trying to filter all items by their username:
app.get("/:username", verify, (req, res) => {
console.log("Welcome to roffys server");
Todo.find({ username: req.params.username }).then((err, todo) => {
if (err) {
console.log("Error retrieving todos");
} else {
res.json(todo);
}
});
});
Verify function,here I'm verifying my auth-token,I console logged it and it is working fine:
const jwt = require("jsonwebtoken");
module.exports = function (req, res, next) {
const token = req.header("auth-token");
console.log("-----token", token);
if (!token) return res.status(401).send("Access Denied");
try {
const verified = jwt.verify(token, "secretkey");
req.user = verified;
} catch (err) {
res.status(400).send("Invalid token");
next();
}
};
FE Side with ReactJS :
componentDidMount() {
const { getAll, setPageCount } = this.props.actions;
axios
.get(`http://localhost:8080/${localStorage.getItem("username")}`, {
headers: {
"auth-token": localStorage.getItem("auth-token"),
},
})
.then((res) => {
getAll(res.data);
setPageCount();
console.log("--------res.data", res.data);
})
.catch((err) => {
console.log("err", err);
});
}
app.get("/:username", verify, (req, res, next) => {
console.log("Welcome to roffys server");
Todo.find({ username: req.params.username }).then((err, todo) => {
if (err) {
console.log("Error retrieving todos");
return next(err);
} else {
res.json(todo);
}
});
});
try to add next to your handler and call it when you receive an error.

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

POST endpoints not working with Express

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

Accessing a passed Object with Express and Axios

In the client side I have :
handleChangeSave(values, id) {
axios.post('/api/users/change' + id, JSON.stringify(values))
.then(resp => {
console.log(resp.data);
})
.catch(function (error) {
console.log(error);
});
}
On the server side I am trying to query for the object and it is coming back empty when it is really not.
router.post('/users/change:id', (req, res) => {
User.findById({ '_id': req.params.id }, (err, user) => {
if(err) return res.status(500).send(err);
let Values = req.query;
console.log(Values); // returns {}
})
});

Resources