Node.js MySQL Tutorial

我們該如何建立 Node.js Express 以及 MySQL ?




 

先新增完資料夾

之後下
npm init

npm install --save express express-handlebars mysql body-parser

npm install --save-dev nodemon

在來建立一個server.js的檔案在一開始新建的資料夾下
在server.js下輸入:
 

const mysql = require('mysql');
const express = require('express');
const bodyParser = require('body-parser');
const mysqlConnection = require('./connection');
const PeopleRoutes = require('./routes/people');

var app = express();
app.use(bodyParser.json());

var mysqlConnection = mysql.createConnection({
  host: XXX,
  user: XXX,
  port: XXX,
  password: XXX,
  database: XXX,
});

mysqlConnection.connect(err => {
  if (!err) {
    console.log('connect');
  } else {
    console.log('connect failed');
  }
});

app.listen(3000);

請在終端機下nodemon server.js
成功連結的話,會出現
​接下來

我們另外新增兩的檔案
叫做people.js、connection.js
在people.js下輸入

const express = require('express');
const Router = express.Router();
const mysqlConnection = require('../connection');

Router.get('/', (req, res) => {
  mysqlConnection.query('SELECT * from people', (err, rows, fields) => {
    if (!err) {
      res.send(rows);
    } else {
      console.log('err query');
    }
  });
});

module.exports = Router;

在connection.js下輸入(主要將server.js的mysqlConnection移過來)

const mysql = require('mysql');
var mysqlConnection = mysql.createConnection({
  host: XXX,
  user: XXX,
  port: XXX,
  password: XXX,
  database: XXX,
});

mysqlConnection.connect(err => {
  if (!err) {
    console.log('connect');
  } else {
    console.log('connect failed');
  }
});

module.exports = mysqlConnection;

更新server.js
 

const express = require('express');
const bodyParser = require('body-parser');
const PeopleRoutes = require('./routes/people');

var app = express();
app.use(bodyParser.json());
app.use('/people', PeopleRoutes);

app.listen(3000);

在MySQL Workbench下新增一個test的database下新增一個people的table裡面加上key and value
在來新增資料進去


就可以直接輸入 我們在server.js輸入的​app.listen(3000);

在網址列上打localhost:3000/people,就成功出現api囉~
參考
如何建立MySQL 
如何建構 CRUD App with Node.js Express and MySQL
使用MySQL Workbench工具,建立帳戶、設定權限