从HTML到node.js以及跨域问题的解决
程序员文章站
2022-05-28 14:06:15
废话不多说,直接上代码 网页客户端 1 2 3 4 5 client ......
废话不多说,直接上代码
网页客户端
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
服务器就启动好了
前端点击发送请求,服务端接收到请求,服务端也返回信息给网页
麻雀虽小五脏俱全,这样一个前端-后端的系统就写好了