axios和ajax学习笔记
~seo 搜素引擎优化,无法被爬虫抓取
~创建多个json连接时使用-p 4000 转换端口
~文件如(图片 注意不是图片地址)不能直接使用json字符串,要使用
先提交表单数据到服务器再获取url网址
data:fd
~使用live-server会自动刷心新页面,所以使用json-server,获取数据控制台会刷新
~回调函数地狱,在一个回调函数不断嵌套回调函数 缺点异常捕获困难,耦合性严重,可读性差
常用的content-type格式
headers: {
// "contecnt-type":"application/x-www-form-urlencoded"
"content-type": "application/json"
},
// body:"name=kerwin&age=100"
body: JSON.stringify({
name: "xiaoming",
age: 180
})
}
http请求报文格式与参数
行 post (url) http/1.1(版本)
头: Host:
Coolkie:
Content-type:
User-Agent:chrome 83
空行
体 (get)为空(post)可以为空
http响应报文格式与参数
行 http/1.1(版本) 404(码) ok
头: (..)
Content-type:
空行
体 <html>
<html>
ajax基础
const xhr = new XMLHttpRequest()
xhr.open("get", "1.json", true)
//第一个 get post
//第二个 请求地址
//第三个 参数 是否异步
xhr.send()
/ 监听readystate属性变化
xhr.onreadystatechange = function(){
// console.log(xhr.readyState)
if(xhr.readyState===4){
if(/^2\d{2}$/.test(xhr.status)){
console.log(JSON.parse(xhr.responseText))
}else{
console.log("error",xhr.responseText)
}
}
}
功能一样但是更建议写下面一条
xhr.onload = function () {
// console.log(xhr.readyState)
if(/^2\d{2}$/.test(xhr.status)){
console.log(JSON.parse(xhr.responseText))
}else{
console.log("error",xhr.responseText)
}
}
ajax请求方式(前端使用json-server严格按照要求,实际后端请求的处理方式由后端自己编写)
get
const xhr = new XMLHttpRequest()
// 直接在地址后面加一个 ?,然后以 key=value 的形式传递
// 两个数据之间以 & 分割
xhr.open('get', './data.php?a=100&b=200')
xhr.send()
post
const xhr = new XMLHttpRequest()
xhr.open('get', './data.php')
// 如果是用 ajax 对象发送 post 请求,必须要先设置一下请求头中的 content-type
// 告诉一下服务端我给你的是一个什么样子的数据格式
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
// 请求体直接再 send 的时候写在 () 里面就行
// 不需要问号,直接就是 'key=value&key=value' 的形式
xhr.send('a=100&b=200')
delete 偏向删除信息
var xhr = new XMLHttpRequest()
xhr.open("DELETE", "http://localhost:3000/users/14", true) //删除id为14的那一个对象
xhr.send()
PATCH (不大写容易错误)修改部分
var xhr = new XMLHttpRequest()
xhr.open("PATCH", "http://localhost:3000/users/14", true)
xhr.setRequestHeader("content-type","application/json") //以json格式
xhr.send(JSON.stringify({
age:180
}))//数据放在
put(改整个)
var xhr = new XMLHttpRequest()
xhr.open("Put", "http://localhost:3000/users/14", true)
xhr.setRequestHeader("content-type","application/json")
xhr.send(JSON.stringify({
username:"guludunzi",
age:180
}))//数据放在
promise自定义封方法
// 1. 定义myAxios函数,接收配置对象,返回Promise对象
function myAxios(config) {
return new Promise((resolve, reject) => {
// 2. 发起XHR请求,默认请求方法为GET
const xhr = new XMLHttpRequest()
xhr.open(config.method || 'GET', config.url)
xhr.addEventListener('loadend', () => {
// 3. 调用成功/失败的处理程序
if (xhr.status >= 200 && xhr.status < 300) {
resolve(JSON.parse(xhr.response))
} else {
reject(new Error(xhr.response))
}
})
xhr.send()
})
}
// 4. 使用myAxios函数,获取省份列表展示
myAxios({
url: 'http://hmajax.itheima.net/api/province'
}).then(result => {
console.log(result)
document.querySelector('.my-p').innerHTML = result.list.join('<br>')
}).catch(error => {
console.log(error)
document.querySelector('.my-p').innerHTML = error.message
})
axios基本使用方法
1. 在 utils/request.js 配置 axios 请求基地址
作用:提取公共前缀地址,配置后 axios 请求时都会 baseURL + url
params{ 键: 键值}
查询参数 查询辽宁省下的内容
注意:在使用过程中键和值会拼接在url
使用axios之前引用
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
get() 默认
<script>
/*
注册用户:http://hmajax.itheima.net/api/register
请求方法:POST
参数名:
username:用户名(中英文和数字组成,最少8位)
password:密码 (最少6位)
目标:点击按钮,通过axios提交用户和密码,完成注册
*/
document.querySelector('.btn').addEventListener('click', () => {
axios({
url: 'http://hmajax.itheima.net/api/register',
method: 'POST',
data: {
username: 'itheima007',
password: '7654321'
}
})
})
</script>
form-serializer()使用
<script>
document.querySelector('.btn').addEventListener('click', () => {
/**
* 2. 使用serialize函数,快速收集表单元素的值
* 参数1:要获取哪个表单的数据
* 表单元素设置name属性,值会作为对象的属性名
* 建议name属性的值,最好和接口文档参数名一致
* 参数2:配置对象
* hash 设置获取数据结构
* - true:JS对象(推荐)一般请求体里提交给服务器
* - false: 查询字符串
* empty 设置是否获取空值
* - true: 获取空值(推荐)数据结构和标签结构一致
* - false:不获取空值
*/
const form = document.querySelector('.example-form')
const data = serialize(form, { hash: true, empty: true })
// const data = serialize(form, { hash: false, empty: true })
// const data = serialize(form, { hash: true, empty: false })
console.log(data)
})
// {username: 'itheima007', password: '7654321'} 结构data
const { username, password } = data
</script>
axios基地址()
1. 在 utils/request.js 配置 axios 请求基地址
作用:提取公共前缀地址,配置后 axios 请求时都会 baseURL + url
async和await的关键字
概念:在async函数内,使用await关键字,获取Promise对象"成功状态"结果值,直接替代.then
用try() catch()捕获错误 这里打印错误要用console.dir()
promise.all 将多个promise合并,其中一个报错,就全部不执行
axios的响应拦截器
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么,例如:直接返回服务器的响应结果对象
const result = response.data
return result;
}, function (error) {
// 超出 2xx 范围的状态码都会触发该函数。
// 对响应错误做点什么,例如:统一对 401 身份验证失败情况做出处理
console.dir(error)
if (error?.response?.status === 401) { //?含义:?用于确保如果error或error.response是null或undefined,则不会尝试访问status属性
alert('身份验证失败,请重新登录')
localStorage.clear()
location.href = '../login/index.html'
}
return Promise.reject(error);
axios和ajax学习笔记
http://localhost:8090//archives/axioshe-ajaxxue-xi-bi-ji