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);
});
});
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.
I want to filter Todo.find by username from axios.get request.The problem is it is not returning anything
Any suggestions?
componentDidMount() {
axios
.get("http://localhost:8080/${username}",{
// username : this.state.username
})
.then((res) => {
this.setState({todos: res.data})
console.log('--------res.data', res.data);
this.setPageCount()
})
.catch((err) => {
console.log("err", err);
});
}
app.get('/', (req, res) => {
console.log('Welcome to roffys server')
Todo.find({username:req.params.username})
.exec((err, todo) => {
if (err) {
console.log('Error retrieving todos')
} else {
console.log(req.body.username)
res.json(todo)
}
})
})
Also I want to send params from other component and I dont know how
This is the function which changes Username,It is in another component:
handleLogIn = () => {
const { username, password } = this.state
if (password.length === 0 || username.length === 0 ) {
alert('Incorrect Login!')
} else {
axios
.post(`http://localhost:8080/logIn`, {
username: username,
password: password,
})
.then((res) => {
this.setState({username: username,password: password})
localStorage.setItem('username',this.state.username)
this.props.history.push("/todoapp");
window.location.reload(false)
console.log(this.state.username)
console.log('res',res)
})
.catch((err) => {
console.log("err", err);
});
}
}
BackEnd Side :
app.get('/:username', (req, res) => {
console.log('Welcome to roffys server')
Todo.find({'username': req.params.username})
.exec((err, todo) => {
if (err) {
console.log('Error retrieving todos')
} else {
res.json(todo)
}
})
})
should be:
`http://localhost:8080/${username}`
not "http://localhost:8080/${username}"
You're incorrectly using the template literal, should be as follows:
.get(`http://localhost:8080/${username}`)
and shouldn't you accept a dynamic param? like this:
app.get('/:username', (req, res) => { // ...
Update:
Regarding transferring the username to the other component, you can do this:
this.props.history.push({
pathname: '/todoapp',
state: { username: this.state.username }
})
and in the todo component:
componentDidMount() {
axios
.get(`http://localhost:8080/${this.props.location.state.username}`)
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);
});
};
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.)
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'
});
});
});