如何处理node.js中的URL?
我是一名学生,我正在做我的目标,
我的目标是,当我单击一个项目时,通过url发送其ID并在Node.js中处理
,例如
http:// localhost:3000/product/:2
is当我单击具有“ 2”作为其ID的项目时,URL。
但是我不知道如何在node.js中处理它。
app.get('/searched.html',async function(req,res){
let db = await getDBConnection();
let rows = await db.all('select * from items');
await db.close();
var output=new Array();
var id = new Array();
var query = url.parse(req.url,true).query;
if(query.productSearch=='All'||query.productSearch==''){
for(let i=0;i<rows.length;i++){
output.push(rows[i]['product_image']);
id.push(rows[i]['product_id']);
}
}else{
for(let i=0;i<rows.length;i++){
if(rows[i]['product_category']==query.productSearch){
output.push(rows[i]['product_image']);
id.push(rows[i]['product_id']);
}
}
}
var output_send = JSON.stringify(output);
var id_send = JSON.stringify(id);
res.render('index',{
data: output_send,
data2 : id_send
});
});
上面的代码是我用来处理查询字符串的代码。
我想我可以重复使用它,但是我不知道如何适当修复它。
你能给我一些提示吗?
I'm a student and I'm doing my H.W.
My goal is, when I click an item, send its id through URL and deal with in node.js
For example,
http://localhost:3000/product/:2
is the url when I clicked the item which has '2' as its ID.
But I don't know how to deal with it in node.js.
app.get('/searched.html',async function(req,res){
let db = await getDBConnection();
let rows = await db.all('select * from items');
await db.close();
var output=new Array();
var id = new Array();
var query = url.parse(req.url,true).query;
if(query.productSearch=='All'||query.productSearch==''){
for(let i=0;i<rows.length;i++){
output.push(rows[i]['product_image']);
id.push(rows[i]['product_id']);
}
}else{
for(let i=0;i<rows.length;i++){
if(rows[i]['product_category']==query.productSearch){
output.push(rows[i]['product_image']);
id.push(rows[i]['product_id']);
}
}
}
var output_send = JSON.stringify(output);
var id_send = JSON.stringify(id);
res.render('index',{
data: output_send,
data2 : id_send
});
});
The code above is the code what I used to deal with query String.
I guess I can reuse it, but I don't know how to fix it appropriately.
Could you give me some hints?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以从URL中获取参数:
/product /2
You can get parameter from url like this :
/product/2