I have local backend on mysql and I am using connect Node.js to connect both of them. Everything is working fine. The connection is succesfull all the queries are happening but why is this not working.
router.get("/:users/:name", (req, res) => {
const { name } = req.params;
console.log(req.params);
mysqlConnection.query(
"SELECT * FROM user WHERE name = ?",
[name],
(error, rows, fields) => {
console.log(rows);
console.log(error);
if (!error) {
res.json(rows);
} else {
console.log(error);
}
}
);
});
whereas it's counterpart is working.
router.get("/:users/:id", (req, res) => {
const { id } = req.params;
mysqlConnection.query(
"select * from user where id = ?",
[id],
(error, rows, fields) => {
if (!error) {
res.json(rows);
} else {
console.log(error);
}
}
);
});
I am using Postman to test my routes. eg: localhost:8080\users\name
I have tried this
router.get("/:users/:name", (req, res) => {
const { name } = req.params;
console.log(req.params);
mysqlConnection.query(
`SELECT * FROM user WHERE name = '${name}'`,
(error, rows, fields) => {
console.log(rows);
console.log(error);
if (!error) {
res.json(rows);
} else {
console.log(error);
}
}
);
});
The issue here is that Express cannot differentiate between
:idand:name; they're both just single string parameters so any matching request will be routed to whatever one is registered first.Assuming that
idis numeric, you can provide more matching information so Express knows where to route requests like/users/123See Route parameters