需要一个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>AJAX GET</title>
<style>
#result {
width: 200px;
height: 100px;
border: solid 2px black;
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result"></div>
</body>
<script>
const btn = document.getElementsByTagName("button")[0];
const result = document.getElementById("result");
btn.onclick = function () {
//创建对象
const xhr = new XMLHttpRequest();
//初始化 设置请求方法和url
xhr.open("GET", "http://127.0.0.1:8000/server");
//问号后面ajax设置的请求参数
// xhr.open("GET",'http://127.0.0.1:8000/server?a=11&b=12&c=13')
//发送
xhr.send();
//事件绑定 处理服务端返回的结果
// on when 当什么时候
//readystate 是xhr对象中的属性,表示状态 0 1 2 3 4
//
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
//判断响应状态码 200 404 403 401 只要是2开头的都表示成功
if (xhr.status >= 200 && xhr.status < 300) {
//处理结果 行头 空行 体
//响应行
// console.log(xhr.status); //状态码
// console.log(xhr.statusText); //状态字符串
//console.log(xhr.getAllResponseHeaders()); //所有的响应头
// console.log(xhr.response); //响应体
result.innerHTML = xhr.response;
} else {
}
}
};
};
</script>
</html>
一个js文件
//引入express
const express = require('express');
//创建应用对象
const app = express();
//创建路由规则
//request是对请求报文的封装
//response是对响应报文的封装
app.get('/server',(request,response)=>{
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
//设置响应体
response.send('HELLO AJAX');
});
//监听端口启动服务
app.listen(8000,()=>{
console.log("服务已经启动,8000端口监听中。。。")
})