node的express中介軟體之static之ajax提交json

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   使用   sp   

 

static中介軟體可以使用戶端直接存取網站中的所有靜態檔案.

利用這個功能可以直接把伺服器上的靜態頁面直接讀取出來返回到用戶端.

從用戶端點擊一個按鈕,向伺服器端發送資料.並且插入到mysql資料庫中去.

 

伺服器端代碼:

 1 var express=require("express"); 2 var app=express(); 3 var mysql=require("mysql"); 4 var pool=mysql.createPool({ 5     host:"localhost", 6     port:3306, 7     database:"test_db", 8     user:"root", 9     password:"gys"10 });11 12 app.use(express.static(__dirname));13 /*app.use(express.static("public"));*/14 app.post("/", function (req,res) {15     req.on("data", function (data) {16         var obj=JSON.parse(data.toString());17         pool.getConnection(function(err,connection){18             if(err) res.send("與mysql資料庫建立串連失敗.");19             else{20                 var str;21                 connection.query("insert into users set ?",{username:obj.username,firstname:obj.firstname}, function (err,result) {22                     if(err) str="在伺服器mysql資料庫中插入資料失敗.";23                     else    str="在伺服器端mysql資料庫匯總插入資料成功.";24                     connection.release();25                     res.send(str);26                 });27             }28         })29     });30 });31 app.listen(1337,"127.0.0.1", function () {32     console.log("開始監聽1337");33 });

 

根目錄下的index.html代碼:

 1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4     <meta charset="UTF-8"> 5     <title>session中介軟體的使用</title> 6     <script type="text/javascript"> 7         function submitData(){ 8             var xhr=new XMLHttpRequest(); 9             xhr.open("post","/",true);10             xhr.onload= function () {11                 if(this.status=200){12                     document.getElementById("res").innerHTML=this.response;13                 }14             };15             var obj={firstname:"郭",username:"延思"};16             xhr.send(JSON.stringify(obj));17         }18     </script>19 </head>20 <body>21 <input type="button" value="提交" onclick="submitData();" />22 <div id="res"></div>23 </body>24 </html>

 

在瀏覽器中鍵入:localhost:1337或localhost:1337/index.html

如果檔案名稱是index.html可以直接這樣寫:localhost:1337

否則就是localhost:1337/檔案名稱

 

node的express中介軟體之static之ajax提交json

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.