Nodejs在连接mysql数据库时只与localhost一起工作。我可以连接到其他主机吗?
这是我的代码
var mysql=require('mysql');
var express=require('express');
const app=express();
var bodyParser=require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended:true
}))
app.get('/',function(req,res) {
return res.send({error:true,message:'working'});
})
app.listen(8080,function() {
console.log('port listening on 8080');
})
const mc=mysql.createConnection({
host:'localhost',
user:'root',
password:'root',
database:'test'
})
mc.connect();
app.get('/users',function(req,res) {
mc.query('select * from sample1',function(err,results) {
if(err) throw err;
console.log(({status:200,data:results}));
return res.send({status:200,data:results});
})
})
app.post('/userslist',function(req,res) {
var id=req.body.id;
console.log(id);
return res.send(id);
})
当我更改主机地址时,它会显示一些错误
port listening on 8080
events.js:137
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 192.168.1.10:3306
at Object._errnoException (util.js:1003:13)
at _exceptionWithHostPort (util.js:1024:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1195:14)
--------------------
at Protocol._enqueue (/var/www/html/nodejs/node_modules/mysql/lib/protocol/Protocol.js:145:48)
at Protocol.handshake (/var/www/html/nodejs/node_modules/mysql/lib/protocol/Protocol.js:52:23)
at Connection.connect (/var/www/html/nodejs/node_modules/mysql/lib/Connection.js:130:18)
at Object.<anonymous> (/var/www/html/nodejs/index.js:21:4)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
我不知道这个错误的原因是什么。我可以摆脱这个问题吗?
答案 0 :(得分:0)
您可能需要调整主机,端口,用户,密码和数据库名称。
确保您拥有正确的配置:
const mc=mysql.createConnection({
host:'localhost',
user:'root',
password:'root',
database:'test'
})