nodejs用express又做了份crud
Posted xiandedanteng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nodejs用express又做了份crud相关的知识,希望对你有一定的参考价值。
感觉crud是高级形式的hello world了。
app代码:
‘use strict‘; var express=require(‘express‘); var http=require(‘http‘); var fs=require(‘fs‘); var app=express(); var mysql=require(‘mysql‘); var pool=mysql.createPool({ host:‘127.0.0.1‘, port:‘3306‘, database:‘test‘, user:‘root‘, password:‘12345678‘, }); app.get(‘/index.html‘,function(req,rsp){ rsp.sendFile(__dirname+‘/index.html‘); }); app.get(‘/add.html‘,function(req,rsp){ rsp.sendFile(__dirname+‘/add.html‘); }); app.get(‘/modify.html/:id‘,function(req,rsp){ rsp.sendFile(__dirname+‘/modify.html‘); }); app.put(‘/list.html‘,function(req,res){ req.on(‘data‘,function(data){ //var obj=JSON.parse(data.toString());// 取得Ajax提交的参数 console.log("list"); pool.getConnection(function(err,connection){ if(err){ res.send(‘Can not connect to MySql DB‘); console.log(err); }else{ var str; connection.query("select * from stock ",function(err,result){ if(err){ str=‘List failed‘; }else{ str="List succeed"; } console.log(str); console.log("result.length="+result.length); var arr=[]; for (var i=0; i<result.length; i++) { var tmp = result[i]; var stock=new Object; stock.id=tmp[‘Id‘]; stock.name=tmp[‘name‘]; stock.code=tmp[‘code‘]; arr.push(stock); } connection.release(); res.send(JSON.stringify(arr)); }) } }); }); }); app.put(‘/add.html‘,function(req,res){ req.on(‘data‘,function(data){ var obj=JSON.parse(data.toString());// 取得Ajax提交的参数 console.log("add "+obj); pool.getConnection(function(err,connection){ if(err){ res.send(‘Can not connect to MySql DB‘); console.log(err); }else{ var str; connection.query(‘insert into stock set ?‘,{name:obj.name,code:obj.code},function(err,result){ if(err){ str=‘Insert failed‘; }else{ str="Insert succeed"; } console.log(str); connection.release(); res.send(str); }) } }); }); }); app.put(‘/del.html‘,function(req,res){ req.on(‘data‘,function(data){ var obj=JSON.parse(data.toString());// 取得Ajax提交的参数 console.log("delete "+obj); pool.getConnection(function(err,connection){ if(err){ res.send(‘Can not connect to MySql DB‘); console.log(err); }else{ var str; connection.query(‘delete from stock where ? ‘,{id:obj.id},function(err,result){ if(err){ str=‘delete failed‘; }else{ str="delete succeed"; } console.log(str); connection.release(); var info={‘status‘:‘ok‘,‘id‘:obj.id} res.send(JSON.stringify(info)); }) } }); }); }); app.put(‘/fetchone.html‘,function(req,res){ req.on(‘data‘,function(data){ var obj=JSON.parse(data.toString());// 取得Ajax提交的参数 console.log("fetchone"); pool.getConnection(function(err,connection){ if(err){ res.send(‘Can not connect to MySql DB‘); console.log(err); }else{ var str; connection.query("select * from stock where ?",{id:obj.id},function(err,result){ if(err){ str=‘fetchone failed‘; }else{ str="fetchone succeed"; } console.log(str); console.log("result.length="+result.length); var arr=[]; for (var i=0; i<result.length; i++) { var tmp = result[i]; var stock=new Object; stock.id=tmp[‘Id‘]; stock.name=tmp[‘name‘]; stock.code=tmp[‘code‘]; arr.push(stock); } connection.release(); res.send(JSON.stringify(arr)); }) } }); }); }); app.put(‘/modify.html‘,function(req,res){ req.on(‘data‘,function(data){ var obj=JSON.parse(data.toString());// 取得Ajax提交的参数 console.log("modify "+obj); pool.getConnection(function(err,connection){ if(err){ res.send(‘Can not connect to MySql DB‘); console.log(err); }else{ var str; connection.query(‘update stock set code=?,name=? where id=? ‘,[obj.code,obj.name,obj.id],function(err,result){ if(err){ str=‘modify failed‘; console.log(err); }else{ str="modify succeed"; } console.log(str); connection.release(); var info={‘status‘:‘ok‘,‘id‘:obj.id} res.send(JSON.stringify(info)); }) } }); }); }); app.listen(8080,"127.0.0.1");
添加页面add.html:
<!DOCTYPE html> <html lang="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <head> <title>add data from db</title> </head> <body > <h3>添加股票</h3> <form id="form1"> 股票代号:<input type="text" id="scode" value=""><br/> 股票名称:<input type="text" id="sname" value=""><br/> <input type="button" value="提交" onclick="addStock();"/> </form> </body> </html> <script type="text/javascript"> <!-- function addStock(){ var obj={ name:document.getElementById("sname").value, code:document.getElementById("scode").value }; var xhr=new XMLHttpRequest(); xhr.open(‘put‘,‘add.html‘,true); xhr.onload=function(e){ if(this.status==200){ //alert(this.response); var retval=this.response.toString(); if(retval==‘Insert succeed‘){ alert(‘插入成功,将转入列表页‘); window.location="/index.html"; } } }; xhr.send(JSON.stringify(obj)); } function gotoAddPage(){ window.location="/add.html" } //--> </script>
列表页面index.html:
<!DOCTYPE html> <html lang="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <head> <title>get data from db</title> </head> <body onload="getAllStocks()"> <table border="1"> <caption>全体股票列表</caption> <tr> <th>id</th><th>code</th><th>name</th><th>删除</th><th>修改</th> </tr> <tbody id="mytable"> </tbody> </table> <br> <a href="javascript:gotoAddPage();">添加</a> </body> </html> <script type="text/javascript"> <!-- function getAllStocks(){ var obj={ name:"none", }; var xhr=new XMLHttpRequest(); xhr.open(‘put‘,‘list.html‘,true); xhr.onload=function(e){ if(this.status==200){ var arr=JSON.parse(this.response); updateTable(arr); } }; xhr.send(JSON.stringify(obj)); } function updateTable(arr){ var table=document.getElementById("mytable"); for(var i=table.childNodes.length-1;i>=0;i--){ table.removeChild(table.childNodes[i]); } for(var i=0;i<arr.length;i++){ var emp=arr[i]; var tr=document.createElement("tr"); tr.setAttribute(‘id‘,emp.id); var td1=document.createElement("td"); td1.appendChild(document.createTextNode(emp.id)); tr.appendChild(td1); var td2=document.createElement("td"); td2.appendChild(document.createTextNode(emp.code)); tr.appendChild(td2); var td3=document.createElement("td"); td3.appendChild(document.createTextNode(emp.name)); tr.appendChild(td3); var td4=document.createElement("td"); var a1=document.createElement("a"); a1.appendChild(document.createTextNode(emp.id)); a1.setAttribute(‘href‘,‘javascript:deleteStock(‘+emp.id+‘)‘); td4.appendChild(a1); tr.appendChild(td4); var td5=document.createElement("td"); var a2=document.createElement("a"); a2.appendChild(document.createTextNode(emp.id)); a2.setAttribute(‘href‘,‘javascript:goModify(‘+emp.id+‘)‘); td5.appendChild(a2); tr.appendChild(td5); table.appendChild(tr); } } function gotoAddPage(){ window.location="/add.html" } function deleteStock(id){ //alert(id); var obj={ id:id, }; var xhr=new XMLHttpRequest(); xhr.open(‘put‘,‘del.html‘,true); xhr.onload=function(e){ if(this.status==200){ var info=JSON.parse(this.response); if(info.status==‘ok‘){ alert(‘删除成功‘); tr=document.getElementById(info.id); tr.parentNode.removeChild(tr); } } }; xhr.send(JSON.stringify(obj)); } function goModify(id){ window.location="/modify.html/"+id; } //--> </script>
修改页面modify.html
<!DOCTYPE html> <html lang="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <head> <title>modify data from db</title> </head> <body onload="fetchStock();"> <h3>修改股票</h3> <form id="form1"> 股票Id:<input type="text" id="sid" value="" readonly><br/> 股票代号:<input type="text" id="scode" value=""><br/> 股票名称:<input type="text" id="sname" value=""><br/> <input type="button" value="提交" onclick="modifyStock();"/> </form> </body> </html> <script type="text/javascript"> <!-- function fetchStock(){ var url=window.location.href.toString(); var pos=url.lastIndexOf("/");// 找最后一个斜杠位置 var id=url.slice(pos+1); var obj={ id:id }; var xhr=new XMLHttpRequest(); xhr.open(‘put‘,‘http://localhost:8080/fetchone.html‘,true);// 注意地址的写法 xhr.onload=function(e){ if(this.status==200){ var arr=JSON.parse(this.response); var stock=arr[0]; document.getElementById(‘sid‘).value=stock.id; document.getElementById(‘scode‘).value=stock.code; document.getElementById(‘sname‘).value=stock.name; } }; xhr.send(JSON.stringify(obj)); } function modifyStock(){ var obj={ id:document.getElementById("sid").value, name:document.getElementById("sname").value, code:document.getElementById("scode").value }; var xhr=new XMLHttpRequest(); xhr.open(‘put‘,‘http://localhost:8080/modify.html‘,true); xhr.onload=function(e){ if(this.status==200){ var info=JSON.parse(this.response); if(info.status==‘ok‘){ alert(‘修改成功‘); window.location="/index.html"; } } }; xhr.send(JSON.stringify(obj)); } //--> </script>
以上是关于nodejs用express又做了份crud的主要内容,如果未能解决你的问题,请参考以下文章
进入全屏 nodejs+express+mysql实现restful风格的增删改查示例
进入全屏 nodejs+express+mysql实现restful风格的增删改查示例
进入全屏 nodejs+express+mysql实现restful风格的增删改查示例
进入全屏 nodejs+express+mysql实现restful风格的增删改查示例