axios:
- axios属于第三方插件,需要引入。
- axios返回的结果是一个Promise对象。
- get方式的请求:
第一种写法
axios.get('http://localhost:8080/xxx.php', {
method : 'get',
params : {
a : 1,
b : 2
}
}).then ( (res) =>{
console.log(res);
}).catch(err = > {
if(err){
console.log(err)
}
})
第二种写法:
axios({
url : 'http://localhost:8080/xxx.php'',
method : 'get',
params : {
a : 1,
b : 2
}
}).then ( ( res ) => {
console.log(res);
}).catch(err => {
if(err){
console.log(err)
})
})
- post请求:
在写post请求前需要做如下几步准备:
1.统一设置请求头:
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
2.使用URLSearchParams实例化一个promise对象
3.使用promise对象的append方法添加数据
代码如下:
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
let params = new URLSearchParams()
params.append('a',1)
params.append('b',2)
new Vue({
el: '#app',
methods: {
axiosGetHandler(){
axios({
url : 'http://localhost:8080/xxx.php'',
method : 'post',
data : params,
headers : {
'Content-Type': "application/x-www-form-urlencoded"
}
}).then(res => {
console.log(res)
}).catch(err =>{
if(err){
console.log(err);
}
})
fetchf方法:
1.get:
new Vue({
el : '.app',
data : {
numobj : {
a : 1,
b : 2
}
},
methods : {
get(){
//输出结果也是promise对象
fetch('http://localhost/get.php?a=1&b=2')
.then(res =>{
res.text();
})
.then(data => {
console.log(data);
})
.catch(err =>{
console.log(err)
})
}
}
})
如果不要传送数据的话:
fetch('data.json')
.then(res => {
res.json() //res.text() res.blob()
})
.then( data => console.log(data) )
.catch (err => console.log(err))
post方式:
post方式和axios一样都需要设置请求头,实例化URLSearchParams,且在fetch的中,post里的数据存储在body中,写法如下:
post(){
fetch('http://localhost/post.php',{
method : 'post',
//设置请求头:
headers : new Header({
'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( err => {
if(err){
console.log(err)
}
})
}