一、本地搭建HTTP服務器
1.使用Node.js在本地搭建HTTP服務器
1)下載安裝Node.js
網(wǎng)址:https://nodejs.org/en
右邊是長期維護版本,左邊是嘗鮮版,推薦下載長期維護版本
2)安裝完成后本地創(chuàng)建文件夾,文件夾名字隨便,我的文件夾名稱是nodeMysqlDemo
3)打開命令行
搜索node關(guān)鍵字,用管理員身份打開node.js command prompt
4)進入D盤,進入剛創(chuàng)建的文件夾
5)依次輸入如下命令
[1] 初始化項目,將會自動創(chuàng)建package.json配置文件
npm init -y
[2] 安裝Express框架,用于快速創(chuàng)建HTTP服務器
npm install express --save
[3] 安裝nodemon監(jiān)控文件修改
npm install nodemon -g
[4] 安裝mysql的軟件包
npm install mysql --save
操作成功后文件夾里面會有這些文件
6)在該目錄創(chuàng)建server.js文件
如果不會創(chuàng)建可以先創(chuàng)建server.txt文本文件,然后把后綴改成js即可
6)打開server.js文件,寫如下服務器端代碼并保存
const express=require('express')
const bodyParser =require('body-parser')
const app=express()
const mysql = require('mysql')
app.use(bodyParser.json())
//處理post請求
app.post('/',(req,res) => {
console.log(req.body)
res.json(req.body)
})
app.post('/show',(req,res)=>{
console.log(req.body.name)
const a=req.body.name
var connection=mysql.createConnection({
host:'localhost',
user:'數(shù)據(jù)庫用戶名',
password:'數(shù)據(jù)庫密碼',
database:'數(shù)據(jù)庫名稱'
})
connection.connect();
connection.query("select * from tb_tags where f_tagID='"+a+"'",function(error,results,fields){
if(error) throw console.error;
res.json(results)
console.log(results)
})
connection.end();
})
app.get('/',(req,res)=>{
var connection = mysql.createConnection({
host:'localhost',
user:'數(shù)據(jù)庫用戶名',
password:'數(shù)據(jù)庫密碼',
database:'數(shù)據(jù)庫名稱'
});
connection.connect();
//查找所有的人物名字返回給客戶端。其實沒必要(測試用的)
connection.query('select * from tb_tags',function(error,results,fields){
if(error) throw error;
res.json(results)
// console.log(results)
})
connection.end();
})
app.listen(3000,()=>{
console.log('server running at http://127.0.0.1:3000')
})
7)最后在命令行運行該文件,啟動服務器
二、微信小程序獲取本地數(shù)據(jù)庫內(nèi)容
1)小程序端數(shù)據(jù)獲取部分代碼
/**
* 生命周期函數(shù)--監(jiān)聽頁面加載
*/
onLoad(options) {
var that = this
wx.request({
url: 'http://127.0.0.1:3000/',
success: function (res) {
console.log(res.data)
// that.setData({ names: res.data })
}
})
},
2)關(guān)閉域名校驗設(shè)置
對于正式上線的項目,小程序要求服務器域名必須在小程序管理后臺中添加,域名必須經(jīng)過ICP備案,且支持HTTPS和WSS協(xié)議,對于開發(fā)人員來說,為了方便學習,可以在微信開發(fā)者工具中關(guān)閉這些驗證,從而利用本地服務器來測試網(wǎng)絡功能。單擊工具欄中的詳情按鈕,找到【不校驗合法域名、web-view(業(yè)務域名)、TLS版本以及HTTPS證書】選項,勾選它即可。--------來自《微信小程序開發(fā)實戰(zhàn)》一書。文章來源:http://www.zghlxwxcb.cn/news/detail-522510.html
3)運行程序,成功獲取本地數(shù)據(jù)庫數(shù)據(jù)
常見錯誤:
數(shù)據(jù)庫沒連接,提示Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol
解決辦法:https://blog.csdn.net/qq_34235767/article/details/127617282文章來源地址http://www.zghlxwxcb.cn/news/detail-522510.html
到了這里,關(guān)于微信小程序開發(fā)之連接本地MYSQL數(shù)據(jù)庫的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!