前端+nodejs+mysql實(shí)現(xiàn)前后端聯(lián)通的完整代碼
創(chuàng)建項(xiàng)目
- 目錄結(jié)構(gòu)
- 創(chuàng)建項(xiàng)目
npm init
初始化項(xiàng)目
一路回車即可
當(dāng)有 package.json
這個(gè)文件的時(shí)候就相當(dāng)于已經(jīng)構(gòu)建完畢
3. 配置package.json
文件
{ "name": "yes", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node index.js" // 設(shè)置啟動(dòng)文件 }, "author": "", "license": "ISC", "dependencies": { "mysql2": "^3.12.0" // 連接數(shù)據(jù)庫的插件 } }
創(chuàng)建
index.js
到根目錄上創(chuàng)建
index.html
文件和index.js平級創(chuàng)建
component
功能性代碼
代碼塊
粘貼上就能用這一套代碼
index.js
// 數(shù)據(jù)庫的方法 let mysqlFunction = require('./compents/heander') // 啟動(dòng)服務(wù)器的方法 let serve = require('./compents/serve') let obj = {} obj['/select'] = mysqlFunction.select obj['/add'] = mysqlFunction.add obj['/del'] = mysqlFunction.del serve.creactServe(obj)
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <div class="abc"></div> <form action="http://localhost:3002/add" method="post"> 名稱<input type="text" name="name"> 年齡 <input type="number" name="age"> 性別 <select name="sex" id=""> <option value="男">男</option> <option value="女">女</option> </select> <button type="submit">新增</button> </form> <body> <script> const abc= document.querySelector('.abc') abc.addEventListener('click',(e)=>{ if (e.target.nodeName=='SPAN') { console.log('點(diǎn)擊了'); var name = e.target.getAttribute('data-name'); console.log(name); del(name) } }) // 刪除 function del(params) { const url = 'http://localhost:3002/del?name='+params; fetch(url, { method: 'GET', }) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); // Parse the JSON from the response }) .then(data => { console.log(data); getdata() }) .catch(error => console.error('Error:', error)); } // 查詢 function getdata(params) { const url = 'http://localhost:3002/select?age=23'; fetch(url, { method: 'GET', }) .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); // Parse the JSON from the response }) .then(data => { let str = `` data.forEach(i=>{ str+=`<div >${JSON.stringify(i)}<span data-name='${i.name}'>刪除<span></div>` }) abc.innerHTML= str }) .catch(error => console.error('Error:', error)); } getdata() </script> </body> </html>
heander.js
這里是設(shè)置功能性代碼的地方并且鏈接數(shù)據(jù)庫的地方
// 引入mysql方法 let http = require('http') let mysql = require('mysql2') let pool = mysql.createPool({ user: 'root', host: 'localhost', password: '123456', port: 3306,//端口號 database: 'mydemo' //連接的數(shù)據(jù)庫 , waitForConnections: true,// 當(dāng)沒有可用連接時(shí)是否等待 connectionLimit: 10, // 最大連接數(shù)量 queueLimit: 0 // 最大等待請求數(shù)量 (0 表示不限制) }) // 連接數(shù)據(jù)庫 pool.getConnection((err) => { if (err) { console.log('連接失敗'); } else { console.log('連接成功'); } }) // res 路徑 和post請求參數(shù) // 查詢 async function select (response, data) { console.log(data); try { response.writeHead('200', { "Content-Type": 'application/json' }) const [reslut] = await pool.promise().query(`select * from school where age=${data.age}`) console.log(reslut); response.end(JSON.stringify(reslut)) } catch (error) { console.log(error); response.writeHead('400', { "Content-Type": 'application/json' }) response.end(JSON.stringify(error)) } } // 新增 async function add (response, data) { console.log(data); try { response.writeHead('200', { "Content-Type": 'application/json' }) let sql = 'insert into school values(?,?,?,?)' let values = [null, data.name, data.age, data.sex] const [reslut] = await pool.promise().query(sql, values) console.log(reslut); response.end(JSON.stringify(reslut)) } catch (error) { console.log(error); response.writeHead('400', { "Content-Type": 'application/json' }) response.end(JSON.stringify(error)) return } } // 刪除 async function del (response, data) { console.log(data); try { response.writeHead('200', { "Content-Type": 'application/json' }) let sql = `delete from school where name='${data.name}'` const [reslut] = await pool.promise().query(sql) console.log(reslut); response.end(JSON.stringify(reslut)) } catch (error) { console.log(error); response.writeHead('400', { "Content-Type": 'application/json' }) response.end(JSON.stringify(error)) return } } module.exports = { select, add, del }
router.js
這個(gè)主要是對于路由做處理,來判斷用戶輸入的接口地址是否正確
// let heander = require('./heander') function route (response, url, data, params) { // console.log(url, data, params); // console.log(data[url]); if (typeof data[url] == 'function') { data[url](response, params) } else { response.writeHead('404', { "Content-Type": 'application/json' }) response.end('{error:請輸入正確路徑}') } } module.exports = route
serve.js
服務(wù)器模塊
let http = require('http') let url = require('url') let route = require('./router') const querystring = require('querystring'); function creactServe (data) { const createserver = http.createServer(async (req, res) => { // // 設(shè)置 CORS 頭部 res.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:5500'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); // 判斷get請求還是post請求 console.log(req.method); if (req.method == 'GET') { route(res, url.parse(req.url, false).pathname, data, url.parse(req.url, true).query) // console.log(req.method); // console.log(url.parse(req.url, true).query); // res.end('{id:1}') } else { let data1 = [] // 這里是post請求 // 獲取post參數(shù) // 出現(xiàn)錯(cuò)誤的時(shí)候 req.on('error', (err) => console.log(err)) // 當(dāng)有數(shù)據(jù)的時(shí)候 req.on('data', (result) => data1.push(result)) // 當(dāng)數(shù)據(jù)傳輸完畢以后 req.on('end', (result) => { data1 = querystring.parse(Buffer.concat(data1).toString()) console.log(data1); route(res, url.parse(req.url, false).pathname, data, data1) // res.end(JSON.stringify(queryString.parse(data1))) }) } // 有人請求了以后才會執(zhí)行這里面的代碼 // req請求,res響應(yīng) // 設(shè)置請求頭 // 返回json類型的格式 }) console.log('服務(wù)器啟動(dòng)成功'); // 設(shè)置端口 createserver.listen('3002', '127.0.0.1') } module.exports = { creactServe }
如何使用
先啟動(dòng)服務(wù),找到終端
npm run start
這個(gè)就是在package.json中配置的
然后再找到index.html
文件
即可開始使用,目前目前功能,增刪查詢
總結(jié)
到此這篇關(guān)于前端+nodejs+mysql實(shí)現(xiàn)前后端聯(lián)通的文章就介紹到這了,更多相關(guān)前端+nodejs+mysql前后端聯(lián)通內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Node.js?中的服務(wù)器相關(guān)概念(常見的服務(wù)器任務(wù))
Node.js?中,服務(wù)器的創(chuàng)建與管理是非常重要的內(nèi)容,Node.js?的非阻塞?I/O?特性使得它特別適合處理高并發(fā)的請求,本文將介紹一些與?Node.js?服務(wù)器相關(guān)的基本概念,包括?HTTP?服務(wù)器、請求和響應(yīng)、路由、以及如何處理常見的服務(wù)器任務(wù),感興趣的朋友一起看看吧2025-04-04基于nodejs+express(4.x+)實(shí)現(xiàn)文件上傳功能
通過一段時(shí)間的查閱資料發(fā)現(xiàn)實(shí)現(xiàn)上傳的方式有:1.express中間件multer模塊2.connect-multiparty模塊(但現(xiàn)在 官方不推薦 )3.使用multiparty模塊實(shí)現(xiàn)4.使用formidable插件實(shí)現(xiàn),本文給大家介紹nodejs+express(4.x+)實(shí)現(xiàn)文件上傳功能,需要的朋友參考下2015-11-11在node中使用jwt簽發(fā)與驗(yàn)證token的方法
這篇文章主要介紹了在node中使用jwt簽發(fā)與驗(yàn)證token的方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-04-04node使用querystring內(nèi)置模塊解決分頁返回?cái)?shù)據(jù)太多導(dǎo)致json.parse()解析報(bào)錯(cuò)問題
這篇文章主要介紹了node使用querystring內(nèi)置模塊解決分頁返回?cái)?shù)據(jù)太多導(dǎo)致json.parse()解析報(bào)錯(cuò)問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-09-09Node.js動(dòng)手?jǐn)]一個(gè)靜態(tài)資源服務(wù)器的方法
這篇文章主要介紹了Node.js動(dòng)手?jǐn)]一個(gè)靜態(tài)資源服務(wù)器的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-03-03Nodejs + sequelize 實(shí)現(xiàn)增刪改查操作
這篇文章主要介紹了Nodejs + sequelize 實(shí)現(xiàn)增刪改查操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11