前后端交互--ajax

tech2022-07-11  140

nodejs中的ajax交互执行步骤(html中)

创建ajax对象( let xhr = new XMLHttpRequest() ||ActiveXObject(“Microsoft.XMLHTTP”);)建立与服务器的连接(xhr.open(‘Mthod’,‘url’));发送网络请求(xhr.send())监听网络请求的整个过程(xhr.onreadstatechange=function*({}))从服务器向前端响应并且发送数据(xhr.responseText)DOM操作

在nodejs中

引入http,fs等模块创建服务并且监听端口在创建的服务中添加回调函数,判断路由并且执行相应的代码

这里常用的两个代码

·res.setHeader("Access-Control-Allow-Origin", "*"); //cors跨域处理res.writeHead(200, {"Content-Type": "text/html;charset=utf-8"})在这里html是不定的完全看你后端服务器传入前端的格式是什么,不修改也不会影响,浏览器也会认识。)if(req.url !="/favicon.ico"){}这里是跳过对网页小图标的请求

主要原理: 在前端页面发送网络请求然后到达服务器,根据传输过来不同的路由做解析,返回到前端不同的值。

eg: html

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <button>开启ajax请求</button> <script type="text/javascript"> function getAjax(method, url) { return new Promise((resolve, reject)=> { // 创建XMLHttpRequest对象 let xhr = new XMLHttpRequest(); // 打开与服务器的链接 xhr.open(method, url); // 监听状态改变,当状态值为4及状态码为200时,表示请求成功 xhr.onreadystatechange = function(){ if(xhr.readyState == 4) { if(xhr.status == 200) { let obj = JSON.parse(xhr.responseText); // Promise状态成功 resolve(obj); } else { reject("出错") } } } // 请求服务器,来获得响应的数据 xhr.send(); }) } // 文档就绪事件 window.onload = function(){ document.querySelector("button").onclick = function() { let promise = getAjax("GET", "http://localhost:9999"); promise.then(data=>{ console.log("data----", data) // DOM操作:更新View let h1 = document.createElement("h1"); h1.innerHTML = data.name + "---" + data.sex + "---" + data.age; document.body.appendChild(h1); }) } } </script> </body> </html>

router.js

module.exports = { home(req,res){ let obj = { "name":"sq", "age":18 } res.end(JSON.stringify(obj)) }, login(req,res){ res.end('login') } }

serve.js

let http =require('http'); let url = require('url'); let router = require('./js/router') http.createServer((req,res)=>{ if(req.url !="/favicon.ico"){ res.setHeader("Access-Control-Allow-Origin", "*"); //cors跨域处理 res.writeHead(200, {"Content-Type": "text/html;charset=utf-8"}) let path = url.parse(req.url).pathname; if(path ==='/'){ router.home(req,res); }else{ router[path.substring(1)](req,res); } } }).listen(9999); console.log('succes');

在最后补充一句,一般我们对原生ajax的操作如下: 在nodejs中首先读取一个html的网页,然后再读取的网页中再通过网络请求去请求资源。比如img css等 但是引用的时候要在router中田间判断路由

最新回复(0)