一、axios 请求常见错误
1、axios is not definde
翻译:axios没有定义
原因:你没有引入,或者文件没有先引入
2、Cananot read properties of undefined (reading "protocol")
翻译:不能使用undefined读取protocol协议
解决:正确的配置url,url是小写
3、.Access to XMLHttpRequest at 'http://www.itcbc.com:3006/api/getbooks' from origin 'null' has been blocked by CORS policy: Method GOT is not allowed by Access-Control-Allow-Methods in preflight response.
- Method GOT is not allowed:请求方式got不被允许
原因:method设置错了
额外说明:1、如果没有指定method,请求将默认使用get方式
2、如果设置了method,要 正确的设置
4、data:{status:1,message:"不存在接口"}
原因:调用的接口时错了,可能是请求方式,或者url错误
解决:调用正确的接口,正确的请求方式和参数
5、axios.js.1155 POST http://www.itcbc.com:3006/api/addbook 400 (Bad Request)
原因:400参数问题
6、400:参数有问题
500:服务器异常
404:路径有问题
401、403:没有授权--token值的处理
二、axios 的使用
1、method:请求方式(参考文档,默认值是get)
2、url:资源的完整路径:服务器地址+资源url
3、result:请求当前接口地址,后台返回的数据
4、axios({配置对象}).then(请求成功之后的回调函数)
三、axios--get 请求
1、带参数方式1——>url?参数=值&参数=值:不要随意添加空格、不要添加引号(默认传递字符串)
这种拼接方式只能用于get方式:
axios({
url: `http://www.itcbc.com:3006/api/getbooks?bookname=${name}&author=${author}`,
method: 'get'
}).then(function(result) {
console.log(result)
2、带参数方式2——>params:固定写死,它是一个对象,对象就是你所需要传递的参数 只能是对象形式,他不能拼接字符串参数
axios({
method: 'get',
url: 'http://www.itcbc.com:3006/api/getbooks',
// 设置参数传递:就是Get方式所需要传递的参数
// 细节:
// 1.params固定写死,只能写这个名字,否则相当于没有传递
// 2.params是一个对象,里面的每组键值对就是一个一个的参数和值
// 3.可以传递多个参数,顺序随意
params: {
bookname: '大家不要随意输入',
id: 111
}
}).then(result => {
console.log(result)
})
})
四、axios--post 请求
1、post方式的参数使用data进行传递
data` 是作为请求主体被发送的数据 //
只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
// 1.获取数据
let bookname = booknameEle.value
let author = authorEle.value
let publisher = publisherEle.value
// 2.发起ajax请求
axios({
url: 'http://www.itcbc.com:3006/api/addbook',
method: 'POST',
// post方式的参数使用data进行传递
data: {
bookname,
author,
publisher
}
}).then(function(result) {
console.log(result)
})
})
五、axios--delete 请求
1、 delete请求方式的参数传递和get一样
六、axios--put 请求
1、完整更新
七、axios--patch请求
1、部分更新