老师 第二段代码是GET请求的使用方法 第三四段代码是POST请求传不同参数的使用方法 第一段代码是什么意思
//
<script src="https://unpkg.com/axios@0.19.2/dist/axios.min.js"></script>
<script>
const URL = "https://www.imooc.com/api/http/search/suggest?words=js";
axios(URL, {
method: "post",
// 请求时的头部信息
headers: {
"Content-Type": "application/x-www-form-urlencoded",
// 'Content-Type': 'application/json'
},
// 通过请求头携带
params: {
username: "YangLiJun",
},
// 通过请求体携带
// "Content-Type": "application/x-www-form-urlencoded",
data: "sex=male&age=18",
// 'Content-Type': 'application/json'
// data: {
// sex: "male",
// age: 18,
// },
// timeout: 10,
// withCredentials: true
})
.then((response) => {
console.log(response.data.data);
})
.catch((err) => {
console.log(err);
});
</script>//GET请求
<script src="https://unpkg.com/axios@0.19.2/dist/axios.min.js"></script>
<script>
const URL = "https://www.imooc.com/api/http/search/suggest?words=js";
axios
.get(URL, {
params: {
username: "YangLiJun",
},
})
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
</script>//POST请求-传名值对形式
<script src="https://unpkg.com/axios@0.19.2/dist/axios.min.js"></script>
<script>
const URL = "https://www.imooc.com/api/http/search/suggest?words=js";
axios
.post(URL, "username=YangLiJun&age=18") //传名值对形式,请求体自动解析Content- Type: application/x-www-form-urlencoded
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
</script>//POST请求-传对象形式
<script src="https://unpkg.com/axios@0.19.2/dist/axios.min.js"></script>
<script>
const URL = "https://www.imooc.com/api/http/search/suggest?words=js";
axios
.post("https://www.imooc.com/api/http/json/search/suggest?words=js", {
username: "YangLiJun", //传对象形式,请求体自动解析Content-Type: application/json;charset=UTF-8,不需要设置Content-Type
age: 18,
})
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
</script>10
收起
正在回答
1回答
同学你好,axios库中提供了一个名为axios的方法,该方法可以通过设置method属性值来决定是post请求还是get请求,所以第一段代码意思是使用axios方法,发送了一个post请求,

祝学习愉快~
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星