从HTML到node.js以及跨域问题的解决

废话不多说,直接上代码

网页客户端

 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

 

 服务器就启动好了

前端点击发送请求,服务端接收到请求,服务端也返回信息给网页

 

 

 

 

 麻雀虽小五脏俱全,这样一个前端-后端的系统就写好了

posted on 2020-01-17 10:03  隔壁小老王  阅读(563)  评论(0编辑  收藏  举报

导航