axios 是封装的第三方库
使用前要引入
<script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script>
axios的get方法
例:
axios({
url: 'http://localhost/get.php',
method: 'get',
params: {
a: 1,
b: 2
}
})
.then( res => {
console.log( res )
})
.catch( error => {
if( error ){
throw error
}
})
axios的post方法
例:
<body>
<div id="app">
<h3> ---------axios get post---------- </h3>
<button @click = "axiosGetHandler"> axios-get </button>
<button @click = "axiosPostHandler"> axios-post </button>
</div>
</body>
<script>
/*
post踩坑之路解决
1. 统一设置请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
2. 使用 URLSearchParams 实例化一个params对象
3. 使用params对象的append方法添加数据
*/
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
let params = new URLSearchParams()
// params.append(key,value)
params.append('a',1)
params.append('b',2)
new Vue({
el: '#app',
methods: {
axiosGetHandler(){
axiosPostHandler(){
/* post 方法 */
axios({
url: 'http://localhost/post.php',
method: 'post',
data: params,
headers: {
'Content-Type': "application/x-www-form-urlencoded"
}
})
.then(res => {
console.log( res )
})
.catch( error => {
if( error ){
throw error
}
})
}
}
})
</script>
fetch 原生
ftech的get方法
<body>
<div id="app">
<h3> fetch-----------get post --------</h3>
<button @click = "get"> get </button>
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
numobj: {
a: 1,
b: 2
}
},
methods: {
get(){
fetch('./data.json')
.then(res=>{
res.json() //res.text() res.blob()
})
.then( data => console.log(data))
.catch( error => console.log( error ))
}
})
</script>
ftech的post方法
例:
<body>
<div id="app">
<button @click = "post"> post </button>
</div>
</body>
<script>
new Vue({
el: '#app',
data: {
numobj: {
a: 1,
b: 2
}
},
post(){
fetch('http://localhost/post.php',{
method: 'post',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交
}),
body: new URLSearchParams([["a", 1],["b", 2]]).toString()
})
.then( res => res.text())
.then( data => console.log( data ))
.catch( error => {
if( error ){
throw error
}
})
}
}
})
</script>
注意
post踩坑之路解决
1. 统一设置请求头
axios.defaults.headers.post[‘Content-Type’] = ‘application/x-www-form-urlencoded’;
2. 使用 URLSearchParams 实例化一个params对象
3. 使用params对象的append方法添加数据
相同点:
都是 Promise
前端原生提供了两种数据请求方式
- ajax
- fetch
切记:
axios fetch post方法都是有坑的 , 一定要注意
解决方法: - 设置请求头
- 通过 new URLSearchParams() 来进行数据传参