weixin_33743703 2017-10-30 00:24 采纳率: 0%
浏览 50

API路由未返回数据

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>
  • 写回答

2条回答 默认 最新

  • Lotus@ 2017-10-30 00:28
    关注

    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.

    评论

报告相同问题?