1. 程式人生 > 其它 >MySQL之旅 nodeJS + express + MySQL 實現介面連線資料庫

MySQL之旅 nodeJS + express + MySQL 實現介面連線資料庫

導言: 由於本人初次嘗試,真的一言難盡啊!遇到很多問題, 問題我會列出來,如果你有好的方法實現歡迎留言!

問題:

1·nodeJS與MySQL版本8.0+衝突問題?

查資料得出結論有以下幾種:

a,MySQL降版本 nodeJs 支援 5.7+版本

b,由於MySQL解除安裝太麻煩了 我選擇的這種是把MySQL密碼改簡單一點,或許這就是加密簡單的原因吧!最後結果是正常連線到資料庫!

以下是MySQL改密碼指令:

ALTER USER ‘root’@‘localhost’ IDENTIFIED WITH mysql_native_password BY ‘修改後的密碼’

重新整理許可權:

FLUSH PRIVILEGES

tips:我的密碼改成超簡單的123,畢竟用來測試嘛

現在步入正題 nodeJs寫的介面連線MySQL資料:

步驟一:確定安裝了node;

檢測安裝指令:

node -v

若沒有安裝:nodeJS傳送門

安裝完成後開始node專案。

步驟二:分以下幾個小步驟

a,選個目錄,起個名 比如 serverNode

b,cd到這個目錄,輸入指令

npm init
npm install body-parser express mysql cors -S

c,根目錄有個app.js檔案,若沒有自己建立一個app.js

var http = require('http');
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');


var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

/**
 * 連線 MySQL 資料庫
 * */ 
var mysql = require('mysql');
var connection = mysql.createConnection({
  host:'127.0.0.1',
  user: 'root',
  password: '123',
  database: 'userslist',
  port: '3306'
});
connection.connect((err) => {
  if(err) throw err;
  console.log(`連線成功`)
});

var app = express();

// 跨域
// 跨域
const cors = require( 'cors');
app.use(cors());

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
// app.use(function(req, res, next) {
//   next(createError(404));
// });


// 跨域  同一站點:協議,域名,埠都一樣的叫做同一個站點
//設定跨域訪問  res.header("Access-Control-Allow-Headers", "X-Requested-With")  || res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');;
// app.all('*', function(req, res, next) {
//     res.header("Access-Control-Allow-Origin", "*");
//     res.header("Access-Control-Allow-Headers", "X-Requested-With");
//     res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
//     res.header("X-Powered-By",' 3.2.1')
//     res.header("Content-Type", "application/json;charset=utf-8");
//     next();
// });

// 介面
app.get('/', (req, res) => {
  res.send('<div>hello world</div>')
})
app.get('/login',(req, res) => {
  res.json('<div>hello login</div>')
})
app.get('/checkMysql', (req, res) => {
  let sql = `SELECT * FROM person`;
  connection.query(sql, (err, result) => {
    if(err){
      console.log(err);
      res.send(`<p>err:${err}</p>`)
    }else{
      console.log(result);
      res.json(result)
    }
  })
})
// 設定埠
app.listen(3434, console.log("application is start at port 3434"));

module.exports = app;
    

tips: 以上全部程式碼,因為下班了,細節我就直接略過了,程式碼有註釋;

啟動node

指令:

npm start

正常啟動後顯示以下內容:

PS D:\server\nodeServer> npm start

> [email protected] start D:\server\nodeServer
> babel-node app

application is start at port 3434
連線成功

最後隨便開啟一個瀏覽器,輸入網址:http://127.0.0.1:3434/checkMysql

會顯示以下內容:

[
    {
        "number": 2,
        "name": "Yaya",
        "birthday": "2021-05-20T16:00:00.000Z",
        "age": 18,
        "member_id": 1,
        "cardID": 622455464,
        "phone": 1399985882,
        "address": null
    },
    {
        "number": 3,
        "name": "Long",
        "birthday": "2021-06-20T16:00:00.000Z",
        "age": 18,
        "member_id": 2,
        "cardID": null,
        "phone": 42221313,
        "address": null
    },
    {
        "number": 1,
        "name": "zhang",
        "birthday": "2021-12-10T16:00:00.000Z",
        "age": 20,
        "member_id": 3,
        "cardID": null,
        "phone": 546513221,
        "address": null
    }
]

我這邊自己用的是postman: 感興趣的朋友可以下載一下:postman傳送門

最後附上截圖: