在express节点js中实现一个简单的搜索栏 [英] implement a simple search bar in express node js
问题描述
所以我尝试实现一种简单的搜索功能进行练习,
so i've tried to implement a simple search functionality to practice,
我的目标是拥有网址"/search/(此处的参数)",并获取名称与参数匹配的产品.
my goal is to have the url "/search/(parameter here)" and get the product who's name matches the parameter.
这是我的中间件:
router.get('/search/:title', function(req, res, next) {
var title = req.params.title;
Product.find({title: title}, function (err, products) {
if(err) {
res.render('shop/search', {products: null});
}
res.render('shop/search', {products: products});
next();
});
});
我不知道为什么,但是它给了我错误:
i don't know why, but it gives me the error:
错误:发送标头后无法设置.
Error: Can't set headers after they are sent.
我不明白为什么要得到它,它说我正在更改标题,对此我有点陌生,我不确定在哪里更改标题?
i can't see why i get this, it says i'm changing headers, i'm kind of new to this and i'm not sure where do i change headers?
推荐答案
在将响应呈现给客户端之后,您将无法调用下一个中间件(即 next()
),也应将其删除.使用 return
语句以停止执行剩余的代码,这是正确的语法:
You cannot call the next middleware ( i.e next()
) after rendering the response to the client, you should remove it, also use return
statement in order to stop the remaining code from executing, here is the correct syntax:
router.get('/search/:title', function(req, res, next) {
var title = req.params.title;
Product.find({title: title}, function (err, products) {
if(err) {
return res.render('shop/search', {products: null});
^^^^^^
}
res.render('shop/search', {products: products});
});
});
这篇关于在express节点js中实现一个简单的搜索栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!