ID作为参数传入,查询无法返回实际存在的行

时间:2015-01-20 10:20:56

标签: mysql node.js express node-mysql

我正在使用node-mysql尝试查询我在本地拥有的熟悉的Northwind数据库。这是我的客户模型:

模型/ customer.js

var connection = require('../../database/connection');

var Customer = {
    list: function(cb) {
        var q = 'select CustomerID, ContactName from Customers limit 10';
        return connection.query(q, cb);
    },
    read: function(id, cb) {
        var q = 'select * from Customers where CustomerID = ' + id;
        return connection.query(q, cb);
    }
};


module.exports = Customer;

好吧,我知道那些类型的查询容易受到SQL注入攻击,但是我来自MongoDB,现在我正在尝试看到我可以在重构它们以确保安全性之前让我的MySQL连接和查询工作。所以这就是我从控制器中调用它们的方式:

控制器/ customers.js

var Customer = require('../models/customer');

var CustomersController = {
    index: function(req, res, next) {
        var data = {};
        Customer.list(function(err, rows) {
            if (err) {
                next(new Error('No customers found!'));
                return;
            }
            data.title = 'All customers';
            data.customers = rows;
            res.render('customers/index', data);
        });
    },
    view: function(req, res, next) {
        var id = req.params.id;
        var data = {};
        Customer.read(id, function(err, row) {
            if (err) {
                next(new Error('The customer with ID ' + id + ' does not exist!'));
                return;
            }
            data.title = row.ContactName;
            data.customer = row;
            res.render('customers/read', data);
        });
    }
};

module.exports = CustomersController;

最后,路线:

var router = require('express').Router();
var CustomersController = require('../../app/controllers/customers');

router.route('/customers')
    .get(CustomersController.index)

router.route('/customers/:id')
    .get(CustomersController.view)

module.exports = router;

GET /customers正在运作,但GET /customers/:id没有。例如,如果我想查看ID为ALFKI的客户的详细信息,我会收到控制器中出现的错误 - “ID ALFKI的客户不存在!”然而,当我使用我在模型中使用的相同查询直接查询数据库时,即select * from Customers where CustomerID = 'ALFKI',将返回一行。

也许一副新鲜的眼睛可以告诉我我做错了什么?

0 个答案:

没有答案