axios --- 发送网络请求
1. 下载
1. 标签引入
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
2. npm下载
npm i -g axios
2. 调用API发送请求
2.1 GET 请求
获取数据
1. 不带参数
axios.get("https://hmajax.itheima.net/api/province")
.then(result => { // 请求成功后的回调函数
// result 就是服务器返回的数据
console.log(result)
})
.catch((e) => { // 当状态码不是200时会报错,被catch捕获到函数
console.log("请求出错了", e)
})
2. 使用?携带查询参数
axios.get("https://hmajax.itheima.net/api/city?pname=河北省")
.then(result => {
// result 就是服务器返回的数据
if (result.status === 200){
console.log(result)
}
})
.catch((e) => {
console.log("请求出错了", e)
})
参数形式携带查询参数发送GET请求
axios.get("https://hmajax.itheima.net/api/city", {
params: {
pname: "山东省"
}
})
.then(result => {
// result 就是服务器返回的数据
if (result.status === 200) {
console.log(result)
}
})
.catch((e) => {
console.log("请求出错了", e)
})
2.2 POST 请求
提交数据
1. 请求体参数
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
3. 配置项发送请求
3.1 GET 请求
获取数据
axios({
url: 'https://hmajax.itheima.net/api/city',
method: 'get', // 默认是get请求,可以省略,并且不区分大小写
params: { // 发送GET请求是params参数配置项
pname: "山东省"
}
})
.then(result => {
console.log(result)
});
3.2 POST 请求
提交数据
axios({
url: 'http://127.0.0.1:8080/api/register',
method: 'post',
data: { // 发送POST请求是data参数配置项
username: 'Fred123',
password: 'Flintstone'
}
})
python防脱发技巧

浙公网安备 33010602011771号