node初體驗完成前後端資訊傳遞,訪問資料庫
阿新 • • 發佈:2020-07-30
1.建立資料夾service
2.shift+右鍵開啟powershell
3.進入資料夾並初始化
4.檢視內容
安裝express包
在service資料夾下建個js檔案
編輯js檔案
constexpress=require('express') constapp=express();//埠號,IP地址 app.listen('8888','192.168.0.105',function(){ console.log('啟動成功') }) app.get('/x1',function(req,res){ res.send('hello') })
ip地址寫自己的
啟動伺服器
如果出錯,ctrl+shift+c返回上一步
啟動後
再次編寫檔案(新增x2)
app.get('/x2',function(req,res){ res.send({ code:0, msg:'請求成功', data : [ {name:'小黑',age :18} ] }) })
重新啟動:
在控制檯按ctrl+shift+c返回上一步
得到結果
//獲取前端get請求發來的資料
再次編寫檔案
//獲取前端get請求發來的資料 app.get('/x3',function(req,res){ console.log(req.query) })
重新啟動:
在控制檯按ctrl+shift+c返回上一步
前端輸入資料
顯示收到的結果
// 傳送檔案
修改檔案
// 傳送檔案 app.get('/x4',function(req,res){ res.sendFile(__dirname + '/1.html'); })
重新啟動:
在控制檯按ctrl+shift+c返回上一步
結果
node連線資料庫
在檔案中引入mysql模組並建立連線
// 引入mysql模組 var mysql=require('mysql'); // 建立連線 var connection =mysql.createConnection({ host :'192.168.0.105', user:'root', password:'123456', database:'music' })
將名為mysql資料庫的user表的第一個localhost改為%,這裡我的不改不能用,訪問不了資料庫,改了就好了
service.js檔案新增
app.get('/x5',function(req,res){ connection.query('select * from song_sheet',function(error,results,fields){ res.send(results) // console.log(results) console.log(error) }) })
重新啟動
我這裡好像之前的不能用了,老師說讓用這個
這個要先裝nodemon,很簡單
然後就找到我的資料庫裡的資訊了。
對資料庫的操作課參考https://www.cnblogs.com/python-django-spid/p/11641830.html
在mysql目錄下開啟powershell,輸入密碼
檢視自己有哪些資料庫
輸入命令:show databases;
檢視這個庫裡都有哪些表的命令: show tables;