I've got this api route setup and it returns data from my staff.json file if I manually type in /api into the browser:
var express = require('express');
var router = express.Router();
var staffData = require('../data/staff.json')
router.get('/api', function(req, res){
res.json(staffData);
});
module.exports = router;
However when I try to make it work in one of my views using this function:
$('#search').click(function(){
$.getJSON('api', function(key,val){
var search = $('#search').val();
var regex = new RegExp('search', 'i');
var output;
$.each(staffData, function(key, val){
if(val.name.search(regex) != -1 || val.email.search(regex)){
output += "<tr>";
output += "<td id='"+key+"'>"+val.name+"</td>";
output += "<td id='"+key+"'>"+val.email+"</td>";
output += "</tr>";
}
});
$('tbody').html(output);
console.log(output);
});
});
I keep getting an error saying staffData is not defined, although it has clearly been defined and returned in my api route.
Can anyone explain what the problem may be?
Regards
</div>
Since you're returning res.json(staffData);
and not rendering a view itself, I'll assume you just use the API to access the data itself in a JSON format. So considering this, the information returned by the API can be accessed in the key
parameter in your $.getJSON
call as you can see in the documentation. Your Node.js API does not run in the browser since it's the server side and the browser, as the client side, does not have any access to the variables declared on the server side for obvious reasons.
When you are trying to get response from api, the response is returned as parameter in callback function. If you want to use the 'staffData' variable, you need to have it in the callback like the function below. Please use the following code.
$('#search').click(function(){
$.getJSON('/api', function(staffData){
var search = $('#search').val();
var regex = new RegExp('search', 'i');
var output;
$.each(staffData, function(key, val){
if(val.name.search(regex) != -1 || val.email.search(regex)){
output += "<tr>";
output += "<td id='"+key+"'>"+val.name+"</td>";
output += "<td id='"+key+"'>"+val.email+"</td>";
output += "</tr>";
}
});
$('tbody').html(output);
console.log(output);
});
});