您好,欢迎访问一九零五行业门户网

Node实现简单的前后端交互

node是前端必学的一门技能,我们都知道node是用的js做后端,在学习node之前我们有必要明白node是如何实现前后端交互的。本文就为大家带来一篇node之简单的前后端交互(实例讲解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望能帮助到大家。
这里写了一个简单的通过原生ajax与node实现的一个交互,刚刚学node的朋友可以看一看。一方面理解服务端与客户端是如何交互的,一方面更熟悉node开发。
先贴代码:(有兴趣的可以copy到本地自己run一下)
主页面的html
index.html:
<!doctype> <html>  <head>   <meta charset="utf-8">   <title></title>  </head>  <body>   <button id="btn1">food</button>   <button id="btn2">other</button>   <h1 id="content"></h1>   <script type="text/javascript" src="./client.js"></script>  </body> </html>
接下来是服务器端的代码,运行方式是在node环境下输入命令:node server.js
server.js:
let http = require('http');  let qs = require('querystring');  let server = http.createserver(function(req, res) {  let body = ''; // 一定要初始化为 不然是undefined  req.on('data', function(data) {   body += data; // 所接受的json数据  });  req.on('end', function() {    res.writehead(200, { // 响应状态    content-type: text/plain, // 响应数据类型    'access-control-allow-origin': '*' // 允许任何一个域名访问   });   if(qs.parse(body).name == 'food') {    res.write('apple');   } else {    res.write('other');   }    res.end();  });  }); server.listen(3000);
引入的qs模块用于解析json
req.on('data', callback);  // 监听客户端的数据,一旦有数据发送过来就执行回调函数
req.on('end', callback); // 数据接收完毕
res  // 响应
客户端的js(功能就是负责一些dom操作以及发送ajax请求)
client.js:
let btn1 = document.getelementbyid('btn1'); let btn2 = document.getelementbyid('btn2'); let content = document.getelementbyid('content'); btn1.addeventlistener('click', function() {  ajax('post', http://127.0.0.1:3000/, 'name='+this.innerhtml); }); btn2.addeventlistener('click', function() {  ajax('post', http://127.0.0.1:3000/, 'name='+this.innerhtml); }); // 封装的ajax方法 function ajax(method, url, val) { // 方法,路径,传送数据  let xhr = new xmlhttprequest();  xhr.onreadystatechange = function() {   if(xhr.readystate == 4) {    if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {     content.innerhtml = xhr.responsetext;    } else {     alert('request was unsuccessful: ' + xhr.status);    }   }  };  xhr.open(method, url, true);   if(val)   xhr.setrequestheader('content-type', 'application/x-www-form-urlencoded');   xhr.send(val); }
这个简单的交互就是这样的,其实我们在第一次学习后端语言的时候第一件事就是写一个前后端交互程序,这样会帮助我们更好的理解前后端的分工。
run方法:
先将server.js运行起来,然后打开html来请求响应。
相关推荐:
关于前后端交互的相关内容汇总
node.js+koa框架实现前后端交互
php前后端交互
以上就是node实现简单的前后端交互的详细内容。
其它类似信息

推荐信息