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

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.

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!