ogbeh ogbeh - 3 years ago 176
Node.js Question

node.js:Can't set headers after they are sent

I am learning Node.js at the moment, and i am trying to create a shopping list application, and i am trying to implement a search route, which checks if the query matches the val, here is the code

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = 3000;

//Array List
let list = ['Fish', 'Lettuce', 'Chicken'];

//Set view engine to pug
app.set('view engine', 'pug');
//use bodyParser

app.get('/', function(request, response){
response.render('list', {list});

app.get('/search', function(request, response){
return list.map(function(val){
if(request.query.search === val){
return response.send('Yup you got ' + val);
response.send('Not found')

app.get('/new-item', function(request, response){

app.post('/add-item', function(request, response){
let add = response.send(request.body);

app.listen(port, function(){
console.log('Listening on Port 3000');

Now the problem is with the
conditional, i know the reason i am getting the error is because i can't use the
twice, i am looking for a way to send either response, based on if the condition is met.
Any help is appreciated

Answer Source

Move response.send('Not found') outside of the loop. Also, you shouldn't use Array.map here, use Array#find instead:

app.get('/search', function(request, response) {
   let foundVal = list.find(function(val) {
     if (request.query.search === val) {
       return val;
   if (foundVal) {
     return response.send('Yup you got: ' + foundVal);
   response.send('Not found');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download