简体   繁体   中英

implement a simple search bar in express node js

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?

You cannot call the next middleware ( ie 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});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM