笔记详情跳转:https://xinze.123.com
express框架
express基本使用
//1、引入express
const express = require("express");
//2、创建应用对象
const app = express();
//3、创建路由规则
// request 是对请求报文的封装
// response 是对响应报文的封装
app.get("/", (request, respone) => {
//设置响应
respone.send("Hello Express");
});
//4、监听端口启动服务
app.listen(3000, () => {
console.log("服务器已经启动,3000 端口监听中....");
});
原生Ajax
GET
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>get</title>
<style>
#result {
width: 200px;
height: 100px;
border: solid 10px pink;
}
</style>
</head>
<body>
<button>点我发送请求</button>
<div id="result"></div>
<script>
//获取button元素
const bth = document.getElementsByTagName("button")[0];
const result = document.getElementById("result");
//绑定事件
bth.onclick = function () {
/* XMLHttpRequest()是一个JavaScript函数,
用于在浏览器和Web服务器之间发送HTTP请求。
它可以让开发人员从浏览器脚本中向服务器发送请求,
然后处理服务器的响应。这对于实现Ajax应用非常有用,
因为它允许浏览器在不刷新页面的情况下与服务器通信。 */
//1、创建对象
const xhr = new XMLHttpRequest();
//2.初始化 设置请求方法和 url
//open:设置请求 两个参数 第一个请求类型 第二个 请求地址
xhr.open("GET", "http://localhost:8000/server?a=11&b=22");
//3.发送请求
xhr.send();
/* onreadystatechange事件:
on when 当...时候
readystate 是xhr 对象中的属性,表示状态 0 1 2 3 4
0: XMLHttpRequest对象创建完成。——还没有调用open()方法 初始化值
1: XMLHttpRequest对象初始化完成。——open()方法调用完毕 已调用send()方法,正在发送请求
2: 请求已经发送——send()方法完成,已经收到全部响应 内容
3: 服务器返回了数据(但是还没有被解析,可能只一段http报文)——正在解析响应内容(服务端返回了结果)
4: 数据解析完成——响应内容解析完成,可以在客户端调用了
change 改变时触发
*/
//4.事件绑定 处理服务端
xhr.onreadystatechange = function () {
//判断(服务端返回了所有的结果)
if (xhr.readyState === 4) {
//判断响应状态码 200 404 403 401 500
//2xx 表示成功
if (xhr.status >= 200 && xhr.status < 300) {
//处理结果 行 头 空行 体
//1.响应行
console.log(xhr.status); //状态码
console.log(xhr.statusText); //状态字符串
console.log(xhr.getAllResponseHeaders); //所有响应头
console.log(xhr.response); //响应体
//设置result的文本
result.innerHTML = xhr.response;
}
}
};
};
</script>
</body>
</html>
POST
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>POST</title>
<style>
#result {
width: 200px;
height: 100px;
border: solid 10px pink;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
//获取result元素
const result = document.getElementById("result");
//绑定事件
/*
addEventListener("mouseover") 是一个 JavaScript 函数,
它能让开发者为 HTML 元素添加鼠标悬停(也称为“鼠标移入”)事件监听器。
这意味着当鼠标指针移动到该元素上方时,会触发指定的 JavaScript 代码。
该函数接受两个参数:event:鼠标悬停事件的名称。在这个例子中,它是 "mouseover":鼠标进入该元素
*/
result.addEventListener("mouseover", function () {
//1、创建对象
const xhr = new XMLHttpRequest();
//2.初始化 设置请求方法和 url
xhr.open("POST", "http://localhost:8000/server");
//设置请求头
xhr.setRequestHeader(
"Content-Type",
"application/x-www-form-urlencoded"
);
//设置自定义请求头 会多一个OPTIONS 请求 响应那边就需要修改接受类型了
xhr.setRequestHeader("name", "xizne");
//3.发送请求 POST发送参数是在 send中发送的
//xhr.send("name=xinze&age=19");
xhr.send("name:xinze&age:19");
//事件绑定
xhr.onreadystatechange = function () {
//判断(服务端返回了所有的结果)
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
//处理服务端返回的结果
result.innerHTML = xhr.response;
}
}
};
});
</script>
</body>
</html>
JSON
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JSON</title>
<style>
#result {
width: 200px;
height: 100px;
border: solid 10px pink;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
//获取result元素
const result = document.getElementById("result");
//绑定事件
window.onkeydown = function () {
//1、创建对象
const xhr = new XMLHttpRequest();
//设置响应体数据的类型
xhr.responseType = "json";
//2.初始化 设置请求方法和 url
xhr.open("POST", "http://localhost:8000/Json-server");
//设置请求头
xhr.setRequestHeader(
"Content-Type",
"application/x-www-form-urlencoded"
);
//3.发送请求 POST发送参数是在 send中发送的
xhr.send("name:xinze&age:19");
//事件绑定
xhr.onreadystatechange = function () {
//判断(服务端返回了所有的结果)
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
//处理服务端返回的结果
//手动对数据转化
/* let data = JSON.parse(xhr.response);
result.innerHTML = data.name + data.age + data.sex; */
//自动转换
result.innerHTML =
xhr.response.name + xhr.response.age + xhr.response.sex;
}
}
};
};
</script>
</body>
</html>
IE缓存问题解决
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>解决IE缓存</title>
<style>
#result {
width: 200px;
height: 100px;
border: solid 10px pink;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
//获取result元素
const result = document.getElementById("result");
//绑定事件
window.onkeydown = function () {
//1、创建对象
const xhr = new XMLHttpRequest();
//2.初始化 设置请求方法和 url 在末尾加上当前时间戳就可以解决
xhr.open("GET", "http://localhost:8000/ie-server?t=" + Date.now());
//3.发送请求 POST发送参数是在 send中发送的
xhr.send("name:xinze&age:19");
//事件绑定
xhr.onreadystatechange = function () {
//判断(服务端返回了所有的结果)
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
result.innerHTML = xhr.response;
}
}
};
};
</script>
</body>
</html>
超时与网络异常
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>超时与网络异常</title>
<style>
#result {
width: 200px;
height: 100px;
border: solid 10px pink;
}
</style>
</head>
<body>
<button>点我发送请求</button>
<div id="result"></div>
<script>
const bth = document.getElementsByTagName("button")[0];
const result = document.getElementById("result");
bth.onclick = function () {
const xhr = new XMLHttpRequest();
//超时设置 2s 设置 2s后没响应取消请求
xhr.timeout = 2000;
//超时回调
xhr.ontimeout = function () {
alert("请求超时,请稍后重试!!");
};
//网络异常回调
xhr.onerror = function () {
alert("你的网络似乎出了些问题!");
};
xhr.open("GET", "http://localhost:8000/delay");
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
result.innerHTML = xhr.response;
}
}
};
};
</script>
</body>
</html>
取消请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>取消请求</title>
</head>
<body>
<button>点击发送</button>
<button>点击取消</button>
</body>
<script>
const bth1 = document.getElementsByTagName("button")[0];
const bth2 = document.getElementsByTagName("button")[1];
const xhr = new XMLHttpRequest();
bth1.onclick = function () {
xhr.open("GET", "http://localhost:8000/delay");
xhr.send();
};
bth2.onclick = function () {
xhr.abort(); //取消请求
};
</script>
</html>
重复请求问题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>重复请求问题</title>
</head>
<body>
<button>点击发送</button>
<button>点击取消</button>
</body>
<script>
//获取元素对象
const bth1 = document.getElementsByTagName("button")[0];
const bth2 = document.getElementsByTagName("button")[1];
const xhr = new XMLHttpRequest();
//标识变量
let flag = false;
bth1.onclick = function () {
//判断 如果正在发送,则取消该请求,创建一个新的
if (flag) xhr.abort;
//修改标识
flag = true;
xhr.open("GET", "http://localhost:8000/delay");
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
//修改标识符
flag = false;
}
};
};
bth2.onclick = function () {
xhr.abort(); //取消请求
};
</script>
</html>
server.js
//1、引入express
const express = require("express");
//2、创建应用对象
const app = express();
//3、创建路由规则
// request 是对请求报文的封装
// response 是对响应报文的封装
//GET
app.get("/server", (request, response) => {
//设置响应头 设置允许跨域
response.setHeader("Access-Control-Allow-Origin", "*");
//设置响应体
response.send("Hello Ajax");
});
//POST
//app.post("/server", (request, response) => {
//all可以接收任意类型的请求
app.all("/server", (request, response) => {
//设置响应头 设置允许跨域
response.setHeader("Access-Control-Allow-Origin", "*");
//响应头
response.setHeader("Access-Control-Allow-Headers", "*");
//设置响应体
response.send("Hello Ajax POST");
});
//JSON
app.all("/Json-server", (request, response) => {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "*");
//设置响应数据
const data = {
name: "xinze",
age: 20,
sex: "男",
};
response.send(data);
});
//解决IE缓存
app.all("/ie-server", (request, response) => {
response.setHeader("Access-Control-Allow-Origin", "*");
//设置响应数据
response.send("HELLO IE -5");
});
//延时响应
app.all("/delay", (request, response) => {
response.setHeader("Access-Control-Allow-Origin", "*");
//设置响应数据
setTimeout(() => {
response.send("HELLO IE -5");
}, 3000);
});
//4、监听端口启动服务
app.listen(8000, () => {
console.log("服务器已经启动,8000 端口监听中....");
console.log("服务器已经启动,请求地址:http://localhost:8000/server");
});
jQuery发送Ajax请求
client.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<title>jQuery 发送 Ajax</title>
<style>
div {
margin-top: 10px;
}
</style>
</head>
<body>
<div>jQuery发送Ajax请求</div>
<div><button>GET</button></div>
<div><button>POST</button></div>
<div><button>通用方法ajax</button></div>
</body>
<script>
$("button")
.eq(0)
.click(function () {
$.get(
"http://localhost:8000/jquery-server",
{ name: "xinze" },
function (data) {
console.log(data);
},
"json"
);
});
$("button")
.eq(1)
.click(function () {
$.post(
"http://localhost:8000/jquery-server",
{ name: "xinze" },
function (data) {
console.log(data);
}
);
});
$("button")
.eq(2)
.click(function () {
$.ajax({
//url
url: "http://localhost:8000/jquery-server",
//参数
data: { name: "xinze", age: 19 },
//请求类型
type: "GET",
//返回类型
dataType: "json",
//成功的回调 声明可参数接收回调传过来的值
success: function (data) {
console.log(data);
},
//超时时间
timeout: 3000,
//失败的回调
error: function () {
console.log("出错了");
},
//头信息
headers: {
name: "xinze",
age: 18,
},
});
});
</script>
</html>
server.js
//1、引入express
const express = require("express");
//2、创建应用对象
const app = express();
app.all("/jquery", (request, response) => {
//设置响应头,设置允许跨域
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "*");
setTimeout(() => {
const data = { name: "xinze", age: 19 };
response.send(data);
}, 1000);
});
//3、创建路由规则
//jQuery
app.get("/jquery-server", (request, response) => {
response.setHeader("Access-Control-Allow-Origin", "*");
const data = { name: "xinze", age: 19 };
response.send(JSON.stringify(data));
//response.send(data);
});
//post
app.post("/jquery-server", (request, response) => {
//设置响应头,设置允许跨域
response.setHeader("Access-Control-Allow-Origin", "*");
const data = { name: "xinze", age: 19 };
response.send(JSON.stringify(data));
});
//4、监听端口启动服务
app.listen(8000, () => {
console.log("服务器已经启动,8000 端口监听中....");
console.log("服务器已经启动,请求地址:http://localhost:8000/server");
});
axios发送Ajax请求
axios.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.2.0/axios.js"></script>
<title>axios 发送 Ajax</title>
<style>
div {
margin-top: 10px;
}
</style>
</head>
<body>
<div>axios 发送 Ajax请求</div>
<div><button>GET</button></div>
<div><button>POST</button></div>
<div><button>通用方法ajax</button></div>
</body>
<script>
const btns = document.querySelectorAll("button");
//配置 baseURL
axios.defaults.baseURL = "http://localhost:8000";
btns[0].onclick = function () {
//get请求
axios
.get("/axios-get", {
//url参数
params: {
id: 100,
vip: 7,
},
//请求头信息
headers: {
name: "xinze ",
age: 19,
},
})
.then((value) => {
console.log(value);
});
};
btns[1].onclick = function () {
//post请求 这里要注意跟get不一样 第二个参数是请求体
axios
.post(
"/axios-post",
{
name: "xinze",
age: 19,
},
{
//请求头信息
headers: {
name: "xinze ",
age: 19,
},
}
)
.then((value) => {
console.log(value);
});
};
btns[2].onclick = function () {
axios({
//请求方法
method: "POST",
//url
url: "/axios",
//url参数
params: {
vip: 10,
level: 30,
},
//头信息
headers: {
a: 100,
b: 200,
},
//请求参数
data: {
name: "xinze",
sex: "男",
},
}).then((response) => {
//响应状态码
console.log(response.status);
//响应状态字符串
console.log(response.statusText);
//响应头信息
console.log(response.headers);
//响应体
console.log(response.data);
});
};
</script>
</html>
server.js
//1、引入express
const express = require("express");
//2、创建应用对象
const app = express();
//3、创建路由规则
//axios
//如果定义了请求头就要 用all
app.all("/axios-get", (request, response) => {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "*");
const data = { type: "GET", name: "xinze", age: 19 };
response.send(data);
//respone.send(data);
});
//post
app.all("/axios-post", (request, response) => {
//设置响应头,设置允许跨域
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "*");
const data = { type: "POST", name: "xinze", age: 19 };
response.send(data);
});
app.all("/axios", (request, response) => {
//设置响应头,设置允许跨域
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "*");
const data = { type: "all", name: "xinze", age: 19 };
response.send(data);
});
//4、监听端口启动服务
app.listen(8000, () => {
console.log("服务器已经启动,8000 端口监听中....");
console.log("服务器已经启动,请求地址:http://localhost:8000/server");
});
fetch发送Ajax请求
fetch.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>fetch 发送 Ajax</title>
<style>
div {
margin-top: 10px;
}
</style>
</head>
<body>
<button>fetch方法ajax</button>
</body>
<script>
const btn = document.getElementsByTagName("button")[0];
btn.onclick = function () {
fetch("http://localhost:8000/fetch?vip=10", {
//请求方法
method: "POST",
//请求头
headers: {
name: "xinze",
},
//请求体
body: "sssssssssss",
})
.then((response) => {
return response.json();
})
.then((response) => {
console.log(response);
});
};
</script>
</html>
server.js
//1、引入express
const express = require("express");
//2、创建应用对象
const app = express();
//3、创建路由规则
//fetch
app.all("/fetch", (request, response) => {
//设置响应头,设置允许跨域
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "*");
const data = { type: "all", name: "xinze", age: 19 };
response.send(data);
});
//4、监听端口启动服务
app.listen(8000, () => {
console.log("服务器已经启动,8000 端口监听中....");
console.log("服务器已经启动,请求地址:http://localhost:8000/server");
});
跨域
同源策略
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>同源策略</title>
</head>
<body>
<h2>xinze</h2>
<button>点我获取用户数据</button>
</body>
<script>
const bth = document.getElementsByTagName("button")[0];
const xhr = new XMLHttpRequest();
bth.onclick = function () {
//这里因为是满足同源策略的,所以 url 可以简写
xhr.open("GET", "/data");
//发送
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.response);
}
}
};
};
</script>
</html>
JSONP原理
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>原理</title>
</head>
<body>
<div id="result"></div>
<script>
//处理数据
function handle(data) {
//获取result元素
const result = document.getElementById("result");
result.innerHTML = data.name;
}
</script>
<!-- js标签也能实现跨域 不过返回来的值必须是个 js表达式 -->
<script src="http://localhost:520/jsonp-server"></script>
</body>
</html>
JSONP实践
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>jsonp实践</title>
</head>
<body>
<input type="text" id="username" />
<p></p>
<script>
//获取元素
const input = document.querySelector("input");
const p = document.querySelector("p");
//处理数据
function handle(data) {
input.style.border = "solid 1px #f00";
p.innerHTML = data.msg;
}
//绑定事件
input.onblur = function () {
//获取用户的输入值
let username = this.value;
//向服务器端发送请求,监测用户名是否存在
//1、创建 script 标签
const script = document.createElement("script");
//2、设置 标签 src 属性
script.src = "http://localhost:520/check-username";
//3、将 script 放入页面中
document.body.appendChild(script);
};
</script>
<!-- js标签也能实现跨域 不过返回来的值必须是个 js表达式 -->
</body>
</html>
jQuery发送JSONP请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script>
<title>jquery发送jsonp请求</title>
</head>
<body>
<button>点击发送请求</button>
<p></p>
<script>
$("button")
.eq(0)
.click(function () {
$.getJSON(
"http://localhost:520/jquery-jsonp-server?callback=?",
function (data) {
console.log(data);
$("p")
.eq(0)
.html(
`名称:${data.name},性别:${data.sex},年龄:${data.age}`
);
}
);
});
</script>
<!-- js标签也能实现跨域 不过返回来的值必须是个 js表达式 -->
</body>
</html>
设置CORS响应头实现跨域
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script>
<title>设置CORS响应头实现跨域</title>
</head>
<body>
<button>点击发送请求</button>
<p></p>
<script>
const b = document.querySelector("button");
b.onclick = function () {
//1、创建对象
const xhr = new XMLHttpRequest();
//2、初始化设置
xhr.open("GET", "http://localhost:520/cors-server");
//3、发送
xhr.send();
//4、绑定事件
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.response);
}
}
//5、判断放回请求
};
};
</script>
</body>
</html>
server.js
const express = require("express");
const app = express();
app.get("/home", (request, response) => {
//响应一个页面
response.sendFile(__dirname + "/1-同源策略/index.html");
});
app.get("/data", (request, response) => {
response.send("用户数据");
});
//jsonp 原理
app.all("/jsonp-server", (request, response) => {
// response.send("console.log('xinze')");
const data = { name: "xinze" };
//将数据转为字符串
let str = JSON.stringify(data);
response.send(`handle(${str})`);
});
//jsonp实践
app.all("/check-username", (request, response) => {
const data = {
exist: 1,
msg: "用户名已存在",
};
//将数据转为字符串
let str = JSON.stringify(data);
response.end(`handle(${str})`);
});
//jquery-jsonp
app.all("/jquery-jsonp-server", (request, response) => {
const data = {
name: "xinze",
age: 19,
sex: "男",
};
//将数据转为字符串
let str = JSON.stringify(data);
//接收 id 参数
let cb = request.query.callback;
// response.end(`handle(${str})`);
response.send(`${cb}(${str})`);
});
//cors
app.all("/cors-server", (request, response) => {
//设置响应头 实现跨域
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Allow-Method", "*");
response.send("hello CORS");
});
app.listen(520, () => {
console.log("服务器已经启动...");
});