廢話不多說,直接上代碼
網頁客戶端
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>client</title> 6 </head> 7 <body> 8 <button onclick="testClick()">點擊</button> 9 <br> 10 <div id ="res_data"></div> 11 <script src="http://code.jquery.com/jquery-latest.js"></script> 12 <script type="text/javascript"> 13 function testClick(){ 14 var HTTPrequest = new XMLHttpRequest(); 15 HTTPrequest.open("POST","http://192.168.3.151:8385/",true); 16 HTTPrequest.setRequestHeader("Content-Type","text/html; charset=utf-8"); 17 HTTPrequest.withCredentials = true; 18 var msg = "this is a request";//新建一個字串,通過send方法發送給服務器 19 HTTPrequest.send(msg); 20 HTTPrequest.onload = function (e){ 21 $('#res_data').append("<p>"+ HTTPrequest.responseText +"</p>");//有回傳資訊時將資訊列印在頁面 22 } 23 HTTPrequest.onerror = function(e){ 24 alert('請求失敗'); 25 } 26 } 27 </script> 28 </body> 29 </html>
實際效果:

就是一個最最簡單的頁面,當點擊頁面按鈕時 將請求發送到服務端
下面是node.js寫的服務端的代碼
1 var http = require('http'); 2 var PORT = 8385; 3 http.createServer(function (req, res) { 4 req.on('data', function(data) { 5 console.log(data.toString()); 6 }); 7 res.setHeader("Access-Control-Allow-Credentials", "true"); 8 res.setHeader("Access-Control-Allow-Origin", "http://192.168.3.151:9000"); 9 res.setHeader("Access-Control-Allow-Headers", "Content-Type"); 10 res.setHeader("content-type", "text/html; charset=utf-8"); 11 var msg = "this is a response"; 12 res.end(msg); 13 }).listen(PORT, function () { 14 console.log('server is listening on port ' + PORT); 15 })
其中 7 8 9 這3行都是為了處理網頁跨域的設定
現在運行這個node

服務器就啟動好了
前端點擊發送請求,服務端接收到請求,服務端也回傳資訊給網頁


麻雀雖小五臟俱全,這樣一個前端-后端的系統就寫好了
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/14467.html
標籤:其他
