1 HTTP协议-请求报文
HTTP协议:规定了浏览器发送及服务器返回内容的格式
请求报文:浏览器按照HTTP协议要求的格式,发送给服务器的内容
1.1 请求报文的格式
请求报文的组成部分有:
请求行:请求方法,URL,协议请求头:以键值对的格式携带的附加信息,比如:Content-Type空行:分隔请求头,空行之后的是发送给服务器的资源请求体:发送的资源
1.2 查看请求报文
首先,运行代码,按F12或右键检查
点击查看源代码就可以看到请求报文了
查看请求体,也可以查看源代码
下面是使用谷歌Google Chrome浏览器查看的请求报文
2 请求报文-错误排查
需求:通过请求报文排查错误原因,并修复输入正确的用户名和密码无法登录
用户名:itheima007
密码:7654321
html,
body {
background-color: #EDF0F5;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.container {
width: 520px;
height: 540px;
background-color: #fff;
padding: 60px;
box-sizing: border-box;
}
.container h3 {
font-weight: 900;
}
.form_wrap {
color: #8B929D !important;
}
.form-text {
color: #8B929D !important;
}
.alert {
transition: .5s;
opacity: 0;
}
.alert.show {
opacity: 1;
}
欢迎-登录
JS中会动态插入提示文字
// 1.获取 alert
const alertCom = document.querySelector('.alert')
// 2.抽取提示框的方法
function showAlert(msg, classname) {
alertCom.innerText = msg
alertCom.classList.add(classname)
alertCom.classList.add('show')
setTimeout(() => {
// 延迟隐藏
alertCom.classList.remove('show')
alertCom.classList.remove(classname)
}, 2000);
}
// 3.给登录按钮绑定点击事件,提交输入的用户信息到服务器
document.querySelector('.btn-login').addEventListener('click', function () {
// 3.1 获取输入的用户名和密码
const username = document.querySelector('.username').value
const password = document.querySelector('.password').value
// 3.2用户名 密码 长度判断
if (username.trim().length < 8) {
showAlert('用户名长度需要大于等于8', 'alert-danger')
return
}
if (password.trim().length < 6) {
showAlert('密码长度需要大于等于6', 'alert-danger')
return
}
// 3.3 通过axios提交到服务器 并 提示用户 成功 / 失败
axios({
url: 'http://hmajax.itheima.net/api/login',
method: 'post',
data: {
username,
password
}
}).then(res => {
// 显示提示框
showAlert(res.data.message, 'alert-success')
}).catch(err => {
// 显示警示框
showAlert(err.response.data.message, 'alert-danger')
})
})
3 HTTP协议-响应报文
HTTP协议:规定了浏览器发送及服务器返回内容的格式
响应报文:服务器按照HTTP协议要求的格式,返回给浏览器的内容
1.相应行(状态行):协议、HTTP响应状态码、状态信息
2.响应头:以键值对的格式携带的附加信息,比如:Content-Type
3.空行:分隔响应头,空行之后的是服务器返回的资源
4.响应体:返回的资源
错误的响应报文
3.1 HTTP响应状态码
用来表明请求是否成功完成
比如:404(服务器找不到资源)
/*
注册用户: http://hmajax.itheima.net/api/register
请求方法: POST
参数名:
username: 用户名 (中英文和数字组成, 最少8位)
password: 密码 (最少6位)
目标: 点击按钮, 通过axios提交用户和密码, 完成注册
需求: 使用axios错误处理语法, 拿到报错信息, 弹框反馈给用户
*/
document.querySelector('.btn').addEventListener('click', () => {
axios({
url: 'http://hmajax.itheima.net/api/registrweer1ddd',
method: 'post',
data: {
username: 'itheima007',
password: '7654321'
}
}).then(result => {
// 成功
console.log(result)
}).catch(error => {
// 失败
// 处理错误信息
// console.log(error)
console.log(error.response.data.message)
// alert(error.response.data.message)
})
})
运行结果: