一、安裝 express 腳手架
使用win+R再輸入cmd打開命令提示符,輸入如下內(nèi)容全局安裝腳手架
npm i express-generator -g
?二、在項目根目錄下創(chuàng)建服務(wù)
可以在命令提示符中cd到自己項目的根目錄下,也可以在HBuilder X里內(nèi)置的終端運行代碼
?C:\HBuilderProjects\wordman> express --view=ejs server
說明:前面是項目的根目錄,express --view=ejs projectName
projectName:名稱,自定義即可
express --view=ejs projectName 的簡寫為 express -e projectName
?創(chuàng)建完成后在根目錄下會出現(xiàn)一個新文件夾
?
cd 到server(或者是你自己自定義的名字)的目錄下
npm install //安裝依賴
npm start //啟動服務(wù)
?在瀏覽器上輸入http://localhost:3000/
出現(xiàn)下圖,代表服務(wù)啟動成功。
?三、連接數(shù)據(jù)庫
在server的目錄下創(chuàng)建db文件夾再創(chuàng)建sql.js文件,如下圖
?在sql.js文件中輸入如下內(nèi)容
?var mysql = require('mysql');
var connection = mysql.createConnection({
?? ?host: '10.101.11.123', //host地址,盡可能寫ip地址,寫localhost在手機(jī)調(diào)試的時候連不上
?? ?port:3306, //端口號
??? user: '賬號', //連接數(shù)據(jù)庫時的賬號
??? password: '密碼',//連接數(shù)據(jù)庫時的密碼
?? ?database: 'wordman' //需要連接的數(shù)據(jù)庫
});
module.exports = connection;
當(dāng)運行的時候有可能出現(xiàn):
文件查找失?。?mysql'
類似于:
?這說明沒有安裝mysql的依賴
解決方法:
打開終端,進(jìn)入到根目錄,輸入npm init -y;
再輸入npm i mysql;
你會看到在根目錄下的node_modules中有
當(dāng) HBuilder X提示你文件查找失敗“文件名”時
很有可能是你的相應(yīng)內(nèi)容沒有下載
?再轉(zhuǎn)到server下的routes文件夾下的index.js文件
?
?輸入內(nèi)容
var express = require('express');
var router = express.Router();
var connection = require('../db/sql.js')
/* GET home page. */
router.get('/', function(req, res, next) {
?? ?res.render('index', {
?? ??? ?title: 'Express'
?? ?});
});//讀取數(shù)據(jù)并存放在/words中
router.get("/words", function(req, res, next) {
?? ?connection.query('SELECT * from level_3_words', function(error, results, fields) {
?? ??? ?if (error) throw error;
?? ??? ?console.log('The solution is: ', results);
?? ??? ?res.send(results)
?? ?});});
module.exports = router;
在瀏覽器中輸入? http://localhost:3000/words
即可得到讀取到的內(nèi)容
?
到這里就算成功連接上mysql數(shù)據(jù)庫了,當(dāng)前端需要讀取這些數(shù)據(jù)時,需要在前端頁面通過url讀取
??? ??? ???? uni.request({
?? ??? ??? ???? url: "http://localhost:3000/words",
?? ??? ??? ??? ?method: 'get',
?? ??? ??? ??? ?success: res => {
?? ??? ??? ??? ???? console.log(res.data);
?? ??? ??? ??? ?}
?? ??? ??? ?})
獲取到數(shù)據(jù)后,有些瀏覽器需要自己點>>打開數(shù)據(jù)
?可以通過
res.data[序號][數(shù)據(jù)名]
獲得相應(yīng)內(nèi)容
如:
res.data[0]['ch_word']
得到上圖ch_word的內(nèi)容
注:
在前后端交互的時候,要先啟動express才能讀取到url中的值。文章來源:http://www.zghlxwxcb.cn/news/detail-456631.html
每次更新server中的內(nèi)容之后需要重新啟動express才能生效,建議安裝一個nodemon,nodemon的效果就是更新內(nèi)容之后不需要重啟express,會自行上傳內(nèi)容,如有需要可自行查閱安裝文章來源地址http://www.zghlxwxcb.cn/news/detail-456631.html
到了這里,關(guān)于uniapp使用express連接mysql數(shù)據(jù)庫的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!