前端+nodejs+mysql實(shí)現(xiàn)前后端聯(lián)通的完整代碼
創(chuàng)建項(xiàng)目
- 目錄結(jié)構(gòu)

- 創(chuàng)建項(xiàng)目


npm init
初始化項(xiàng)目

一路回車(chē)即可
當(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ù)庫(kù)的插件
}
}
創(chuàng)建
index.js到根目錄上
創(chuàng)建
index.html文件和index.js平級(jí)創(chuàng)建
component功能性代碼
代碼塊
粘貼上就能用這一套代碼
index.js
// 數(shù)據(jù)庫(kù)的方法
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">
名稱(chēng)<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));
}
// 查詢(xún)
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ù)庫(kù)的地方
// 引入mysql方法
let http = require('http')
let mysql = require('mysql2')
let pool = mysql.createPool({
user: 'root',
host: 'localhost',
password: '123456',
port: 3306,//端口號(hào)
database: 'mydemo' //連接的數(shù)據(jù)庫(kù)
, waitForConnections: true,// 當(dāng)沒(méi)有可用連接時(shí)是否等待
connectionLimit: 10, // 最大連接數(shù)量
queueLimit: 0 // 最大等待請(qǐng)求數(shù)量 (0 表示不限制)
})
// 連接數(shù)據(jù)庫(kù)
pool.getConnection((err) => {
if (err) {
console.log('連接失敗');
} else {
console.log('連接成功');
}
})
// res 路徑 和post請(qǐng)求參數(shù)
// 查詢(xún)
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è)主要是對(duì)于路由做處理,來(lái)判斷用戶(hù)輸入的接口地址是否正確
// 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:請(qǐng)輸入正確路徑}')
}
}
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請(qǐng)求還是post請(qǐng)求
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請(qǐng)求
// 獲取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)))
})
}
// 有人請(qǐng)求了以后才會(huì)執(zhí)行這里面的代碼
// req請(qǐng)求,res響應(yīng)
// 設(shè)置請(qǐng)求頭
// 返回json類(lèi)型的格式
})
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文件

即可開(kāi)始使用,目前目前功能,增刪查詢(xún)
總結(jié)
到此這篇關(guān)于前端+nodejs+mysql實(shí)現(xiàn)前后端聯(lián)通的文章就介紹到這了,更多相關(guān)前端+nodejs+mysql前后端聯(lián)通內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Node.js 使用 gRPC從定義到實(shí)現(xiàn)過(guò)程詳解
gRPC是一個(gè)高性能、開(kāi)源的遠(yuǎn)程過(guò)程調(diào)用(RPC)框架,由 Google 開(kāi)發(fā),它支持多種編程語(yǔ)言,旨在簡(jiǎn)化和優(yōu)化分布式系統(tǒng)中的服務(wù)通信,本文給大家介紹Node.js 使用 gRPC從定義到實(shí)現(xiàn)過(guò)程,感興趣的朋友跟隨小編一起看看吧2024-07-07
Node.js?子線(xiàn)程Crash?問(wèn)題的排查方法
這篇文章主要介紹了Node.js?子線(xiàn)程Crash?問(wèn)題的排查,本文通過(guò)代碼例子給大家詳細(xì)講解,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06
快速刪除 node_modules 目錄的集中方法(多種方法)
本文介紹了三種快速刪除node_modules目錄的方法:使用rimraf工具、通過(guò)npx運(yùn)行rimraf以及在Windows命令提示符中使用del命令,每種方法都適合不同的操作系統(tǒng)和使用場(chǎng)景2024-11-11
npm?install安裝失敗報(bào)錯(cuò):The?operation?was?rejected?by?your?
這篇文章主要給大家介紹了關(guān)于npm?install安裝失敗報(bào)錯(cuò):The?operation?was?rejected?by?your?operating?system的相關(guān)資料,文中給出了多種解決方法供大家參考學(xué)習(xí),需要的朋友可以參考下2023-04-04
詳解使用抽象語(yǔ)法樹(shù)AST實(shí)現(xiàn)一個(gè)AOP切面邏輯
這篇文章主要為大家介紹了使用抽象語(yǔ)法樹(shù)AST實(shí)現(xiàn)一個(gè)AOP切面邏輯的簡(jiǎn)單方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04

