最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - implement a simple search bar in express node js - Stack Overflow

programmeradmin1浏览0评论

so i've tried to implement a simple search functionality to practice,

my goal is to have the url "/search/(parameter here)" and get the product who's name matches the parameter.

this is my middleware:

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?

so i've tried to implement a simple search functionality to practice,

my goal is to have the url "/search/(parameter here)" and get the product who's name matches the parameter.

this is my middleware:

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?

Share Improve this question asked Feb 2, 2018 at 19:15 phantttomphantttom 871 gold badge2 silver badges8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

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

res.render(..) can only be called once for a request. Therefore you should add an else statement as follows:

if(err)
    res.render('shop/search', {products: null});
else
    res.render('shop/search', {products: products});
发布评论

评论列表(0)

  1. 暂无评论