工具:VScode,node,以及VScode内部下载express插件,浏览器启动插件(运行html)
通过终端输入命令express npm install express -g
然后输入npm i express --save.
写好代码后,在相应的目录通过node server.js启动服务端
再从html上发送请求,我的html中如果要查看是否发送成功,在html运行后的网页上按F12即可观看交互结果.
__________当看不明白时,上哔哩哔哩搜索尚硅谷AJAX,老师讲的挺明白.
发送GET请求的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 1px;
}
</style>
</head>
<body>
<button >点击发送请求</button>
<div id="result"></div>
<script>
//获取button元素
const btn = document.querySelector("button");
//绑定事件
btn.onclick = function(){
//创建对象
const xhr = new XMLHttpRequest();
//初始化 设置请求方法和url
xhr.open('GET','http://127.0.0.1:8000/server');
//发送
xhr.send();
//事件绑定 处理服务端返回的结果
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
if(xhr.status>=20&&xhr.status<300){
//处理结果 行 头 空行 体
//1.响应行
console.log(xhr.status);
console.log(xhr.statusText);
console.log(xhr.getAllResponseHeaders);
console.log(xhr.response);
}
}
}
}
</script>
</body>
</html>
接受请求的服务端sever.js
// 1.引入express
const express = require('express');
//2.创建对象
const app = express();
// 3.创建路由规则
app.get('/server',(request,response)=>{
//设置响应头
response.setHeader('Access-Control-Allow-Origin',"*");
//设置响应体
response.send('hello ajax get');
})
app.post('/server',(request,response)=>{
//设置响应头
response.setHeader('Access-Control-Allow-Origin',"*");
//设置响应体
response.send('hello ajax post');
})
//监听端口启动服务
app.listen(8000,()=>{
console.log("服务已启动....");
})