TypeError: Object [object Object], [object Object] has no method find

TypeError: Object [object Object], [object Object] has no method find

我正在学习一本名为 "Sitepoint Full Stack Javascript with MEAN" 的书中的教程,我刚刚完成第 6 章,并且应该创建一个 "server" 和一个 "database"。数据库只不过是一个 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,'.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.js开("database")

[
    {
        "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
        }
    }


]

希望能帮到你。

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

本书第 80 页:

The find Method A quick note about the find method. It is in the spec for ECMAScript 6 but is currently unavailable in the Node runtime as of Node version 0.10.32. For this example, you can add a polyfill for the Array.find method. A polyfill is a term used to describe code that enables future JavaScript features in environments that are yet to support it. You can also write an additional method in lib/employees that locates an element in an array based on an ID. This bit of code will be removed once a true

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

    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;
}

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

The program as is will continue to respond with 'static file maybe' to every request not intercepted by the preceding routing tests.

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