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){
response.render('new');
});
app.post('/add-item', function(request, response){
let add = response.send(request.body);
list.push(add);
});
app.listen(port, function(){
console.log('Listening on Port 3000');
});
/search
if
response.send
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');
});