I'm working on a little project and although it all works, I think I might be doing it in an incorrect way. The front end consists of a simple form that gathers input data (make and color) and once submitted, it sends the input data to a POST endpoint in express via AJAX and gets filtered to return the items I need in a JSON file. Once the data posts, I use another AJAX call to get the filtered data back to my front end to display. Again this all works, but I'm posting and getting from the same route in express. Is this all good or can I accomplish this in a better manner?
Front end:
var carList = [];
form.addEventListener('submit', function(e) {
e.preventDefault();
var make = document.querySelector('.make').value.toLowerCase(),
color = document.querySelector('.color').value.toLowerCase();
$.ajax({
method: 'POST',
url: '/cars',
data: {
make: make,
color: color
},
success: function(data) {}
});
$.ajax({
method: 'GET',
url: '/cars',
success: function(data) {
carList = data;
populateList();
}
});
});
ExpressJS:
function readJSONFile(filename, callback) {
fs.readFile(filename, (err, data) => {
if(err) {
callback(err);
return;
}
try {
callback(null, JSON.parse(data));
} catch(exception) {
callback(exception);
}
});
}
let make = '',
color = '';
app.get('/cars', (req, res) => {
let newList = [];
readJSONFile('cars.json', (err, json) => {
var items = json.cars.filter((item) => {
if (item.type.toLowerCase() == make || item.color.toLowerCase() == color) {
newList.push(item);
}
});
if (err) throw err;
res.send(newList);
});
});
app.post('/cars', (req, res) => {
make = req.body.make;
color = req.body.color;
});