目录
网络
- 不管是客户端,还是服务器,他们都是一个应用程序,而不是一台计算机。客户端和服务器可以分布在不同的计算机上,也可以在同一台计算机上,并不需要特殊看待,大部分后端开发的就是服务器程序,前端的Node技术也能开发服务器程序
- 客户端和服务器的这种交互模式称之为[经典c/s结构](client/server)。在这种结构中,如果客户端是浏览器,则我们称之为b/s结构(broser/server)。
- 服务器程序往往是为了互联网产品提供服务,因此又称之为web服务器。
- 一次完整的交互,总是从请求开始,响应结束。
-->请描述什么叫做服务器,客户端,请求,响应,c/s,b/s
请求:我向服务器发
响应:服务器给我发
完整的url地址
协议 + 主机 + 端口 + 路径 + 参数 + hash
http://www.duyiedu.com:8888/news/2022?page=1&limit=10#main
请求行:高度概括了客户端想要干什么
请求方法 + 路径 + 参数 + hash
请求头:描述了请求的一些额外信息
请求体:包含了要给服务器传递的正文数据,请求体是可以省略的
ajax
XHR
var xhr = new XMLHttpRequest(); //创建发送请求的对象
xhr.onreadystatechange = function(){
//当请求状态发生改变时运行的函数
//xhr.readyState:一个数字,用于判断请求到了哪个阶段
//1:open方法已被调用
//2:send方法已被调用
//3:正在接收服务器的响应消息体
//4:服务器响应的所有内容均已接收完毕
if(xhr.readyState === 4){
console.log("服务器的响应结果已经全部收到")
const obj = JSON.parse(xhr.responseText);//将获取到的数据转为JSON格式
}
//xhr.getResponseHeader("Content-Type") 获取响应头Content-Type
}
xhr.open("GET" , "http://localhost:7001/api/herolist") //配置请求
//xhr.setRequestHeader("Content-Type","application/json"); //设置请求头
xhr.send(null); //构建请求体,发送到服务器,如果没有请求体,传递null
Fetch API
fetch("http://localhost:7001/api/herolist") //等待响应头,然后
.then((resp)=> resp.json()) // 等待响应体,然后
.then((resp)=> { // 获取数据
const a = resp.data;
})
例:
<body>
<p>账号:<input type="text" id="txtLoginId"></p>
<p>密码:<input type="password" id="txtLoginPwd"></p>
<p><button>登录</button></p>
<script>
const btn = document.querySelector("button");
const txtLoginId = document.querySelector("#txtLoginId");
const txtLoginPwd = document.querySelector("#txtLoginPwd");
btn.onclick = async function(){
const loginId = txtLoginId.value;
const LoginPwd = txtLoginPwd.value;
const obj = {
loginId,
loginPwd,
};
const resp = await fetch("http://localhost:7001/api/user/login",{//全为异步
method: "POST", //看接口文档
headers:{
"Content-Type": "application/json", //看接口文档
},
body:JSON.stringify(obj),
});
const body = await resp.json();
if(body.code){
alert(body.msg);
}
else{
alert("登录成功");
}
}
</script>
</body>
axios
第一种写法
axios.get("http://study.duyiedu.com/api/herolist").then((resp)=>{
console.log(resp); //resp.data为响应体的数据,axios会自动解析JSON格式
})
第二种写法
(async function(){
const resp = await axios.get("http://study.duyiedu.com/api/herolist");
console.log(resp.data);
})();
路径配置
axios
.get("http://study.duyiedu.com/api/herolist",{ //等于在herolist后面加loginId=a&k=3,且不需要转义
params:{
loginId: "a&k=3",
a:1,
b:2,
}
})
.then((resp)=>{
console.log(resp); //resp.data为响应体的数据,axios会自动解析JSON格式
})
发post请求
axios
.post("http://study.duyiedu.com/api/herolist",{
loginId:"abc",
loginPwd:"123123",
nickname:"棒棒鸡"
})
.then((resp)=>{
console.log(resp); //resp.data为响应体的数据,axios会自动解析JSON格式
})
也可以创建实例,可以省略前面路径
const instance = axios.create({
baseURL:"http://study.duyiedu.com/"
})
instance.get("/api/herolist").then(resp=>{
。。。。
})
http状态码
200:一切正常
301:资源已被永久重定向
302:资源已被临时重定向
304:文档内容未被修改
400:语义错误,当前请求无法被服务器理解
403:服务器拒绝执行
404:资源不存在
500:服务器内部错误