【问题标题】:TypeError: Object [object Object], [object Object] has no method findTypeError: Object [object Object], [object Object] has no method find
【发布时间】:2015-03-19 21:10:08
【问题描述】:

我在一本名为“Sitepoint Full Stack Javascript with MEAN”的书中学习了一个教程,我刚刚完成了第 6 章,应该已经创建了一个带有“数据库”的“服务器”。数据库只不过是一个 JSON 文档。 然而,即使(我可以看到),我的代码是他的直接副本,当我尝试运行它时,我得到了标题中提到的错误。 var result = data.find(function(item) {...(位于 employees.js 中的行,大约第 16 行)是导致此问题的原因。我看不出我还能做什么,希望你们能找到解决我问题的方法。

我有几个不同的文件用于此目的。

Index.js:

var http = require('http');
var employeeService = require('./lib/employees');
var responder = require('./lib/responseGenerator');
var staticFile = responder.staticFile('/public');

http.createServer(function(req,res) {
    // a parsed url to work with in case there are parameters
    var _url;

    //In case the client uses lower case for methods
    req.method = req.method.toUpperCase();
    console.log(req.method + ' ' + req.url);

    if (req.method !== 'GET') {
        res.writeHead(501, {
            'Content-Type': 'text/plain'
        });
        return res.end(req.method + ' is not implemented by this server.');
    }

    if (_url = /^\/employees$/i.exec(req.url)) {
        //return a list of employess
        employeeService.getEmployees(function(error, data){
            if(error) {
                return responder.send500(error, res);
            }
            return responder.sendJson(data,res);
        });
    } else if (_url = /^\/employees\/(\d+)$/i.exec(req.url)){ 
        //find the employee by the id in the route
        employeeService.getEmployee(_url[1], function(error, data) {
            if (error) {
                return responder.send500(error, res);
            }
            if(!data) {
                return responder.send404(res);
            }
            return responder.sendJson(data,res);
        });

    } else{
            res.writeHead(200);
            res.end("static file")
    }


}).listen(1337);

console.log('server running');

employee.js

var employeeDb = require('../database/employees.json')

exports.getEmployees = getEmployees;
exports.getEmployee = getEmployee;

function getEmployees (callback) {
    setTimeout(function() {
        callback(null, employeeDb);
    }, 500);
}

function getEmployee (employeeId, callback) {
    getEmployees(function (error, data) {
        if (error) {
            return callback(error);
        }
        var result = data.find(function(item) {
            return item.id === employeeId;
        });
        callback(null, result)
    });
}

responseGenerator.js

var fs = require('fs');

exports.send404 = function (reponse) {
    console.error('Resource not found');
    response.writeHead(404, {
        'Content-Type': 'text/plain'
    });
    response.end('Not Found');
}

exports.sendJson = function(data, response) {
    response.writeHead(200, {
        'Content-Type': 'application/json'
    });

    response.end(JSON.stringify(data));
}

exports.send500 = function(data, response) {
    console.error(data.red);
    reponse.writeHead(500, {
        'Content-Type': 'text/plain'
    });
    response.end(data);
}

exports.staticFile = function(staticPath) {
    return function(data, response) {
        var readStream;

        // Fix so routes to /home and /home.html both work
        data = data.replace(/^(\/home)(.html)?$/i,'$1.html');
        data = '.' + staticPath + data;

        fs.stat(data, function(error, stats) {
            if (error || stats.isDirectory()) {
                return exports.send404(response);
            }

            readstream = fs.createReadStream(data);
            return readStream.pipe(response);
        });
    }
}

employees.json("数据库")

[
    {
        "id": "103",
        "name": {
            "first": "Colin",
            "last": "Ihrig"
        },
        "address": {
            "lines": ["11 Wall Street"],
            "city": "New York",
            "state": "NY",
            "zip": 10118
        }
    },
    {
        "id": "104",
        "name": {
            "first": "Idiot",
            "last": "Fjols"
        },
        "address": {
            "lines": ["Total taber"],
            "city": "Feeeee",
            "state": "Whatever",
            "zip": 10112
        }
    }


]

希望你能帮忙。

【问题讨论】:

  • 嗯.. employees.json 没有 find 方法。 (这是一个数组,所以这是意料之中的。)如果这段代码是直接从书中复制的,我不确定它想教你什么。
  • 看来您可能打算改用 .filter
  • 是的,.filter 成功了!谢谢。
  • 您只是在使用旧版本的节点,请尝试使用 iojs。 Array#find 是一种新方法。

标签: javascript json node.js mean-stack


【解决方案1】:

书的第 80 页:

find 方法 关于 find 方法的简要说明。它在规范中 对于 ECMAScript 6,但目前在 Node 运行时中不可用 节点版本 0.10.32。对于这个例子,你可以为 Array.find 方法。 polyfill 是一个术语,用于描述以下代码: 在尚未实现的环境中启用未来的 JavaScript 功能 支持它。您还可以在 lib/employees 中编写附加方法 根据 ID 定位数组中的元素。这段代码 一旦为真就会被移除

如果您下载了本书的源代码,您可以看到作者为使 find 方法可用所做的工作:

    Array.prototype.find = function (predicate) {
  for (var i = 0, value; i < this.length; i++) {
    value = this[i];
    if (predicate.call(this, value))
      return value;
  }
  return undefined;
}

【讨论】:

    【解决方案2】:

    您可以尝试使用 .filter 方法而不是 .find 方法。或者将数据库中的数组更改为 json。

    【讨论】:

    【解决方案3】:

    index.js(最后一个else 块) Em-Ant 指出:

    程序将继续以“可能的静态文件”响应 每个请求都没有被前面的路由测试拦截。

    https://github.com/spbooks/mean1/issues/3

    【讨论】:

      猜你喜欢
      • 2013-12-25
      • 1970-01-01
      • 1970-01-01
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多