express.js
//引入express
const { response } = require('express')
const express = require('express')
//创建应用对象
const app = express()
//创建路由规则
app.get('/server', (request, response) => {
//设置相应
response.setHeader('Access-Control-Allow-Origin','*')
response.send('hello express')
})
//监听端口启用服务
app.listen(8000, () => {
console.log('服务已启动,8000端口监听中');
})
index.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>Document</title>
</head>
<body>
<div id="myDiv">
<button onclick="handleAjax()" >点击</button>
</div>
<script>
function handleAjax() {
var xmlhttp = new XMLHttpRequest()
//向服务器端发送请求
xmlhttp.open("get", "http://127.0.0.1:8000/server ");
xmlhttp.send();
//处理服务端的返回结果
/*
readyState 0 未初始化
readyState 1 open方法调用完毕
readyState 2 send方法调用完毕
readyState 3 服务端返回了部分结果
readyState 4 服务端返回了所有的结果
*/
xmlhttp.onreadystatechange = function () {
//只有在readyState == 4 && xmlhttp.status响应状态码 进行处理
/*
响应状态码 2开头都是成功 200<=status<300
*/
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//处理结果
console.log(xmlhttp.status);//响应状态码
console.log(xmlhttp.statusText);//响应状态字符串
console.log(xmlhttp.getAllResponseHeaders);//所有响应头
console.log(xmlhttp.response);//响应体
}
}
}
</script>
</body>
</html>