廢話很少說,直接上代碼javascript
網頁客戶端html
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>
實際效果:前端
就是一個最最簡單的頁面,當點擊頁面按鈕時 將請求發送到服務端java
下面是node.js寫的服務端的代碼node
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行都是爲了處理網頁跨域的設置jquery
如今運行這個node後端
服務器就啓動好了跨域
前端點擊發送請求,服務端接收到請求,服務端也返回信息給網頁服務器
麻雀雖小五臟俱全,這樣一個前端-後端的系統就寫好了app