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 {}
})
});
Related
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.
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);
});
};
I'm stuck I'd like to get all the ratings for a fablab and can't get the code to be asynchronous.
So here I get an empty array since the code is not async.
This is my example :
// get all ratings for a fablab
rating_router.get('/get/:id', (req, res) => {
Fablab.findById({_id:req.params.id}, (err, fablab) => {
if(err) send(err)
else {
let ratingstest = []
fablab.rating.map(ratingID => {
Rating.findById({_id:ratingID}, (err, rating) => {
if(err) send(err)
else ratingstest.push(rating)
})
})
return ratingstest
}
})
})
You could add a conditional to check when the last query resolves and then pass the array of results to res.send:
rating_router.get('/get/:id', (req, res) => {
Fablab.findById({ _id: req.params.id }, (err, fablab) => {
if (err) {
res.send(err)
}
else {
let ratingstest = []
fablab.rating.forEach(ratingID => {
Rating.findById({ _id: ratingID }, (err, rating) => {
if (err) {
res.send(err)
}
else {
ratingstest.push(rating)
// Check if this is the last one
if (ratingstest.length == fablab.rating.length) {
res.send(ratingstest)
}
}
})
})
}
})
})
However, it might be nicer to use promises:
rating_router.get('/get/:id', (req, res) => {
Fablab
.findById({ _id: req.params.id })
.then(fablab => fablab.rating || [])
.then(ratingIDs => ratingIDs.map(ratingID =>
Rating.findById({ _id: ratingID })
))
.then(ratingArr => Promise.all(ratingArr))
.then(result => res.send(result))
.catch(err => res.send(err))
})
I hope this helps.
Inside mapping function, make findById promise
function findByIdPromise(){
return new Promise((resolve,reject)=>{
Rating.findById({_id:ratingID}, (err, rating) => {
if(err) reject(err)
else {
ratingstest.push(rating)
resolve()
}
})
})
}
After mapping is done, you'll have array of promises, then just do
Promise.all(fablab.rating).then(()=>console.log(ratingstest))
Hi friends I'm trying to find in my subDoc category string matching
Here is the code:
router.get('/:_categoryName', (req, res, next) => {
Malgezot.findOne({ 'items.category': req.params._categoryName }, (err, malgezot) => {
if(err) return res.render('body/category', {info: ''});
console.log(malgezot);
});
});
But the results is all of the items!
I also tried:
router.get('/:_categoryName', (req, res, next) => {
Malgezot.find({'items': { 'category': req.params.categoryName }}, (err, malgezot) => {
if(err) return res.render('body/category', {info: ''});
console.log(malgezot);
});
});
If your data is in form of object then query should be :
router.get('/:_categoryName', (req, res) => {
const { _categoryName } = req.params;
Malgezot.findOne({
'items.category': _categoryName
}).then((data) => {
if (data) {
res.status(200).json(data)
}
}).catch((err) => {
res.status(500).json({
message: 'Internal server error'
});
});
});
Or if your data in form of array then your query should be:
router.get('/:_categoryName', (req, res) => {
const { _categoryName } = req.params;
Malgezot.findOne({
item : { $in : [{ category: _categoryName }] }
}).then((data) => {
if (data) {
res.status(200).json(data)
}
}).catch((err) => {
res.status(500).json({
message: 'Internal server error'
});
});
});
I am making a quite easy CRUD application in MEAN stack.
I have succesfully done all but Update function. Problem is not with request itself but inability of Node server to respond. Request is making changes to database as requested and I even eget a { n: 1, nModified: 0, ok: 1 } response from mongojs.
However, I am unable to send it back to Angular frontend.
I try res.json() but it won't all allow me as it is a not a function? But I am succesfuly doing res.json in create, delete and read. In network tab in developers console, request seems to be pending and after like 30 seconds it throws an error.
No luck with postman either.
How can I send a response to frontend?
// Error handling
const sendError = (err, res) => {
response.status = 501;
response.message = typeof err == 'object' ? err.message : err;
res.status(501).json(response);
};
// Response handling
let response = {
status: 200,
data: [],
message: null
};
// Update log <-- doesn't send response but works
router.put('/update/:id', (req, body, res) => {
console.log("Received UPDATE request");
console.log(req.params.id);
const bodyToUpdate = {
'_id': mongojs.ObjectId(req.params.id),
'week': req.body.week,
'type': req.body.type,
'text': req.body.text,
'days': req.body.days
};
console.log(bodyToUpdate);
db.logs.update({
_id: mongojs.ObjectId(req.params.id)}, bodyToUpdate, (err, res) => {
if (err) return next(err);
response.data = res;
res.json(response);
console.log(response);
});
});
// Delete log <--does work without problems
router.post('/delete/:id', (req, res) => {
console.log("Received DELETE request");
console.log(req.params.id);
db.logs.remove({
_id: mongojs.ObjectId(req.params.id)}, (err, users) => {
if (err) return next(err);
console.log(response);
response.data = users;
res.json(response);
});
});
Service API frontend
deleteLog(id) {
return new Promise((resolve, reject) => {
this._http.post('/api/delete/' + id , id)
.map(res => res.json())
.subscribe(res => {
resolve(res);
console.log(res);
}, (err) => {
reject(err);
});
});
}
updateLog(logToUpdate) {
return new Promise((resolve, reject) => {
this._http.put('/api/update/' + logToUpdate._id, logToUpdate)
.map(res => res.json())
.subscribe(res => {
resolve(res);
// console.log(res);
}, (err) => {
reject(err);
});
});
}
As #JithinSebastian correctly pointed out - I should not have 3 arguments in put request. I also had to change name of callbacks in mongo update function because I already used res in router function callback.
// Update log
router.put('/update/:id', (req, res) => {
console.log("Received UPDATE request");
console.log(req.body);
const bodyToUpdate = {
'_id': mongojs.ObjectId(req.params.id),
'week': req.body.week,
'type': req.body.type,
'text': req.body.text,
'days': req.body.days
};
db.logs.update({
_id: mongojs.ObjectId(req.params.id)
}, bodyToUpdate, (err, logs) => {
if (err) return next(err);
response.data = logs;
res.json(response);
console.log(response);
});
});