不是技术分享,存粹回忆遗忘在角落的知识
AJAX
在这个 axios, fetch 盛行的时代,对于原生 JavaScript 的 ajax 技术就遗忘在角落。所以,需要拾起回忆。
在正题开始之前,先大致了解下:
- axios 的本质:
- 在客户端使用,就是基于
ajax(XMLHttpRequest)封装实现的。 - 在服务端使用,就是基于 node 的
http 模块的实现。
- 在客户端使用,就是基于
- fetch 是 ES6 才出现(新的 api ),被称为下一代 ajax 技术,基于 promise 实现的。
正题开始了。
ajax 是 Asynchronous JavaScript And XML 的缩写,其内部结合了 XMLHttpRequest 对象。
ajax 的优点:
- 不刷新页面更新网页
- 在页面加载后从服务器请求数据
- 在页面加载后从服务器接收数据
- 在后台向服务器发送数据
ajax 的使用步骤:
- 创建实例对象
- 向服务器发送请求、携带参数(
open,send) - 监听服务端的响应(监听状态的变化,
onreadystatechange)
客户端代码
// 1. 创建 xhr 实例对象
const xhr = new XMLHttpRequest();
// 2. 向服务器发送请求
/*
参数一:请求方法
参数二:请求地址
参数三:判断是否是同步(false)还是异步(true,默认)
*/
xhr.open("POST", "http://localhost:3000/list", true);
/*
针对 get 请求:send()
针对 post 请求:send(string)
*/
xhr.send();
// 3. 监听状态的回调函数
xhr.onreadystatechange = function () {
// this 指向 xhr 实例对象
if (this.readyState === 4 && this.status === 200) {
console.log(JSON.parse(this.responseText));
}
};
服务端进行处理跨域。
服务端代码
const Koa = require("koa");
const KoaRouter = require("@koa/router");
const cors = require("@koa/cors");
const app = new Koa();
const router = new KoaRouter();
// 中间件的应用
app.use(async (ctx, next) => {
ctx.code = "200";
next();
});
router.post("/list", async (ctx) => {
ctx.body = {
code: ctx.code,
list: [
{ name: "copyer", age: 12 },
{ name: "james", age: 13 },
],
};
});
// 手动设置跨域
// app.use(async (ctx, next) => {
// ctx.set("Access-Control-Allow-Origin", "*");
// ctx.set(
// "Access-Control-Allow-Headers",
// "Content-Type,Content-Length,Authorization,Accept,X-Requested-With"
// );
// ctx.set("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
// if (ctx.method == "OPTIONS") {
// ctx.body = 200;
// } else {
// await next();
// }
// });
app.use(cors()); // 插件处理跨域
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000, () => {
console.log("The Service is running!!!");
});
针对 ajax 的详细信息还是去 w3cshool 去回忆一下:www.w3school.com.cn/js/js_ajax_…
websocket
websocket 是 HTML5 新出的一种是实时通讯协议,基于 tcp 协议。
为了创建 Websocket 连接,需要通过浏览器发出请求,之后服务器进行回应,这个过程通常称为“握手”(handshaking)。
客户端代码
<body>
<button onclick="sendMessage()">start消息</button>
<button onclick="closeMessage()">stop消息</button>
<div id="show"></div>
<script type="text/javascript">
const showContent = document.querySelector("#show");
var ws = new WebSocket("ws://localhost:3001");
let timer = null;
//客户端向服务端连接成功后,执行
ws.onopen = () => {
console.log("连接建立");
};
// 服务端发送消息,触发
ws.onmessage = (data) => {
showContent.innerHTML = data.data;
};
// dom 事件
function sendMessage() {
timer = setInterval(() => {
ws.send("客服端发送的消息" + Date.now());
}, 2000);
}
function closeMessage() {
if (timer) {
clearInterval(timer);
}
}
</script>
</body>
常用的 api:
onopen: 连接成功后回调onmessage: 接收到服务端的消息后回调send: 向服务端发送消息onclose: 关闭之后回调onerror: 报错后回调
更多 websocket 信息看阮一峰大佬:www.ruanyifeng.com/blog/2017/0…
服务端代码
借用了 ws 三方库:
const Koa = require("koa");
const app = new Koa();
let WebSocketServer = require("ws").Server;
const websocket = new WebSocketServer({ host: "localhost", port: 3001 });
// 客户端向服务端发起连接,进入此回调
websocket.on("connection", (req, res) => {
console.log("连接成功");
// 监听客户端发送的消息
req.on("message", function (data) {
// 拿到客户端的消息,过 200 ms 在进行发送给客户端
setTimeout(() => {
req.send("服务端加工后的:" + data.toString());
}, 200);
});
});
app.listen(3000, () => {
console.log("The Service is running!!!");
});
总结
遗忘的知识,要时不时进行回忆,不然就是新知识。