首页 > 解决方案 > 如何将 node.js 连接到 MySQL

问题描述

我正在尝试将 node.js 连接到 MySQL 并且失败了。我已经安装了 MySQL 和相关库。如何解决此错误?另外,如果我想将数据获取到 react-native,我应该怎么做呢?

const express = require('express');
const mysql = require('mysql');

const connection = mysql.createPool({
  host     : '*****',//aws db endpoint/MySQL hostname
  user     : 'administrator', // username of MySQL connection
  password : '*****', //pw of MySQL db
  database : 'database_3' // name of database to be used
});

const app = express();
app.get('/User', function (req, res) {
    connection.getConnection(function (err, connection) {
    connection.query('SELECT * FROM User', function (error, results, fields) {
      if (error) throw error;
      res.send(results)
    });
  });
});

// Starting our server.
app.listen(3306, () => {
    console.log('Go to http://localhost:3306/User');
   });
   

收到的错误消息:

events.js:174
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::3306
    at Server.setupListenHandle [as _listen2] (net.js:1279:14)
    at listenInCluster (net.js:1327:12)
    at Server.listen (net.js:1414:7)
    at Function.listen (C:\Users\Irvin\my-new-project\node_modules\express\lib\application.js:618:24)
    at Object.<anonymous> (C:\Users\Irvin\my-new-project\route.js:39:5)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
Emitted 'error' event at:
    at emitErrorNT (net.js:1306:8)
    at process._tickCallback (internal/process/next_tick.js:63:19)
    at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

标签: javascriptmysqlnode.jsreactjsreact-native

解决方案


错误:监听 EADDRINUSE:地址已在使用 :::3306

这意味着该端口3306已在使用中,请尝试将其更改为另一个端口或停止在该端口上运行的进程。

// Lets change 3306 to 3307
app.listen(3307, () => {
    console.log('Go to http://localhost:3307/User');
});

如果您想停止此端口上的进程,这里是如何在 linux 上执行此操作


推荐阅读