req.getConnection不是express-myconnection中的函数 [英] req.getConnection is not a function in express-myconnection

查看:74
本文介绍了req.getConnection不是express-myconnection中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试连接mysql,但它向我显示 req.getConnection不是函数波纹管是我使用的代码片段.在app.js中

i am trying to connect mysql, but it is showing me req.getConnection is not a function Bellow is the code snipet which i have used. In app.js

var mysql = require('mysql'), 
connection = require('express-myconnection'), 
dbOptions = { 
  host: 'localhost',
  user: 'root', password: '',
  port: 3306,
  database: 'nodejs'
 }; 
app.use(connection(mysql, dbOptions, 'request'));

在Customers.js中

exports.list = function(req, res, next) { 
  req.getConnection(function(err, connection) { 
    if (err) return next(err); 
  connection.query('SELECT * FROM customer', function(err, rows) {
 if (err) console.log("Error Selecting : %s ", err); 
   res.render('customers', { 
     page_title: "Customers - Node.js", data: rows 
   }); 
  }); 
  });
 };

能否请您检查做错了什么.我在nodejs中还很陌生,所以可能是我缺少了一些东西.

Can you please check what is have done wrong. I am pretty new in nodejs, so may be i am missing something.

如果您想检查我的完整软件包,请遵循以下网址,我已将所有代码推送到我的git存储库中 https://github.com/chiraggmodi/nodeCrud

If you want to check my complete package, please follow bellow URL, i have push all code in my git repository https://github.com/chiraggmodi/nodeCrud

推荐答案

您需要移动以下行:

app.use(connection(mysql, dbOptions, 'request'));

现在,它在您的路由之后声明为 ,这意味着请求将永远不会通过它(这就是Express的工作方式:请求通过它们的声明顺序通过中间件和路由处理程序传递).

Right now, it's declared after your routes, which means that requests will never pass through it (that's how Express works: requests are passed through both middleware and route handlers in order of their declaration).

如果在需要 req.getConnection()的路由之前在代码中的某个位置使用它(也许

If you use it to a location in the code before the routes that require req.getConnection() to work (perhaps here), requests will first pass through the express-myconnection middleware and then get passed to the route handlers, making sure that req.getConnection() will be available inside those route handlers.

编辑:仔细观察,您的客户路线也不正确.

EDIT: on closer look, your customer routes are also incorrect.

您有这个:

router.get('/', function(req, res, next) {
  res.render('customers', customers.list);
});

但是 customer.list 本身就是一个路由处理程序,而不是您应该传递给 res.render()的东西.相反,请尝试以下操作:

But customer.list is a route handler in itself, not something you should pass to res.render(). Instead, try this:

router.get('/', customers.list);

(以及类似的 customers_route中的所有其他路由.js )

(and similarly for all the other routes in customers_route.js)

这篇关于req.getConnection不是express-myconnection中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆