英文:
Why is routing to 'name' not working when it works for 'id'?
问题
以下是您提供的代码的翻译部分:
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);
}
}
);
});
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 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);
}
}
);
});
答案1
得分: 1
这里的问题是 Express 无法区分 :id
和 :name
;它们都只是单个字符串参数,因此任何匹配的请求都会路由到先注册的那个。
假设 id
是数字,你可以提供更多匹配信息,这样 Express 就知道要将请求路由到哪里,比如 /users/123
。
// 首先注册更具体的路由
router.get("/users/:id(\\d+)", (req, res) => {
const { id } = req.params;
// 其他操作...
});
// 其次注册更一般的路由
router.get("/users/:name", (req, res) => {
const { name } = req.params;
// 其他操作...
});
参见 路由参数。
英文:
The issue here is that Express cannot differentiate between :id
and :name
; they're both just single string parameters so any matching request will be routed to whatever one is registered first.
Assuming that id
is numeric, you can provide more matching information so Express knows where to route requests like /users/123
// register the more specific route first
router.get("/users/:id(\\d+)", (req, res) => {
const { id } = req.params;
// etc...
});
// register the more general route second
router.get("/users/:name", (req, res) => {
const { name } = req.params;
// etc...
});
See Route parameters
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论