filter GET request with params - node.js

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

Related

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

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

How to write a function like middleware but can have some parameters

I want to modify the function (checkAuth) to check if a User have a specific Permissions. If yes => continue, else will print the error. But it return 'undefinded'.
I want to pass two parameters (userId and Permission_CODE). I get userId from parsing token.
I used middleware but it seemed not allow to pass other parameters (except req, res, next)
This is for Windows server, running NodeJS and Express
checkToken.js
const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
try {
const token = req.headers.authorization.split(" ")[1];
const decoded = jwt.verify(token, 'secretKey')
req.decoded = decoded
next();
}
catch(error){
return res.status(401).json({
message: "Auth failed"
})
}
}
checkAuth.js
const User = require('../models/user')
module.exports = (userId, action_code) => {
User
.findOne({ _id: userId })
.populate({
path: 'user_role',
populate: {
path: 'permissions',
match: { action_code: action_code }
}
})
.exec((err, user) => {
if (err) {
return console.log(err)
}
else if (user.user_role.permissions.length == 0) {
return false
}
else {
console.log(user.user_role.permissions)
return true
}
})
}
}
Using in API
router.get('/luu',checkToken,(req, res) => {
console.log(checkAuth(req.decoded.userId, "1")) //It returned undefinded
})
This is the code of program: https://github.com/phongluudn1997/express-testing.git
In checkAuth.js, your module is asynchronous, according to this you can't just return true/false, you've to return result in a callback.
module.exports = (userId, action_code, cb) => {
User
.findOne({ _id: userId })
.populate({
path: 'user_role',
populate: {
path: 'permissions',
match: { action_code: action_code }
}
})
.exec((err, user) => {
if (err) {
return cb(err, false)
}
else if (user.user_role.permissions.length == 0) {
return cb(null, false);
}
else {
console.log(user.user_role.permissions)
return cb(null, true);
}
})
}
}
And you must call your module like this:
router.get('/luu',checkToken,(req, res) => {
checkAuth(req.decoded.userId, "1", function(err, result){
if(err) console.log(err);
else if(!result) console.log("False");
else console.log("True");
});
})
You're trying to return from callback which does not work. You could use async/await like:
module.exports = async (userId, action_code) => {
let permission;
try {
const user = await User
.findOne({ _id: userId })
.populate({
path: 'user_role',
populate: {
path: 'permissions',
match: { action_code: action_code }
}
})
if (user.user_role.permissions.length == 0) {
permission = false
} else {
console.log(user.user_role.permissions)
permission = true
}
} catch (e) {
throw e
}
return permission
}
Make your route async function as well:
router.get('/luu',checkToken, async (req, res) => {
try {
console.log(await checkAuth(req.decoded.userId, "1"))
} catch (e) {
console.error(e)
}
})
or make this into another middleware function like:
// checkPermission.js
module.exports = (req, res, next) => {
User
.findOne({ _id: userId })
.populate({
path: 'user_role',
populate: {
path: 'permissions',
match: { action_code: action_code }
}
})
.exec((err, user) => {
if (err) {
return next(err)
}
else if (user.user_role.permissions.length == 0) {
req.permissions = false
}
else {
console.log(user.user_role.permissions)
req.permissions = true
}
})
next();
}
Then in your route:
const checkPermission = require('./checkPermission.js')
router.get('/luu',checkToken, checkPermission, (req, res) => {
console.log(req.permissions)
})

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