mysql查询在nodeJS中返回undefined

此代码返回一个错误,因为“结果(mysql.query)”返回未定义的值。 我用mysql命令行创build了一个7〜10行的数据库表,并且数据库在workbench和command shell都能正常工作。 是因为我安装了一个错误的方式吗? 或代码错误? 我已经在另一台计算机上testing了相同的东西,并从那里完美地工作,突然它不起作用。 我没有复制文件,只是写了/从内存中input相同的东西。

我已经search了stackoverflow,似乎每个人都谈论asynchronous问题,这不是真正的我的情况(同样的事情以前工作)

用npm安装mysql,mysql版本是社区5.7

crudserver.js(主文件)

const fs = require("fs"); //filesystem const ejs = require("ejs"); const mysql = require("mysql"); const express = require("express"); //handles all the middlewares const bodyParser = require("body-parser"); //handles "POST" const client = mysql.createConnection({ user:"****", password:"****", database:"testdb" }); let app = express(); app.use(bodyParser.urlencoded({ extended:false })); app.listen(52273, function(){ console.log("server running at http://127.0.0.1:52273"); }); app.get("/",function (request,response){ fs.readFile("crudlist.ejs","utf8",function(error,data){ client.query("SELECT * FROM products", function(error,results){ response.send(ejs.render(data,{ data:results, mytitle:"title1", mytitlesub:"title2" })); }); }); }); 

crudlist.ejs

  <% data.forEach(function (itm,index){ %> some codes.... <% } > 

它说'数据'是不确定的。

不能在eval(eval编译(F:\ mycoding \ node_modules \ ejs \ lib \ ejs.js:549:12),:17:12)在returnedFn(F:\ mycoding \ node_modules \在F:\ mycoding \ crudserver上的Object.exports.render(F:\ mycoding \ node_modules \ ejs \ lib \ ejs.js:384:37)在F:\ mycoding \ node_modules \ mysql \ lib \ protocol \目录下的Query.Sequence.end(F:\ mycoding \ node_modules \ mysql \ lib \ protocol \ sequences \ Sequence.js:88:24) Protocol.js:398:18在Array.forEach(本机)在F:\ mycoding \ node_modules \ mysql \ lib \ protocol \ Protocol.js:397:13 at _combinedTickCallback(internal / process / next_tick.js:73:7) at process._tickCallback(internal / process / next_tick.js:104:9)

如果data undefined ,则很可能有一个您决定不处理的错误:

 // note the first parameter of callback function - "error" client.query("SELECT * FROM products", function(error,results){ 

您应该testing是否存在error ,并仅在没有error时才显示结果。

问题解决了:重新安装了mySQL。 设置端口默认为3306.我在安装时确实将端口设置为一些自定义数字,这是问题的真正原因。 除非有必要,否则不要从3306更改端口号。