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.

    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧