ajax
axios
axios.get
//方式一
axios.get('/user?id=12345')
.then((res) => {
console.log(res)
}).catch((error) => {
console.log(error);
})
//方式二
let params = { id: 12345 }
axios.get('/user', { params })
.then((res) => {
console.log(res);
}).catch((error) => {
console.log(error);
})
axios.post
//方式一
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
//方式二
axios({
methods: 'post',
url: 'http://jsonplaceholder.typicode.com/users',
data: {
name: 'qiurx'
}) .then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
- Content-Type: application/json
let params = { id: 12345 }
axios.post('/user', params)
.then((res) => {
console.log(res);
}).catch((error) => {
console.log(error);
})
- Content-Type: application/x-www-form-urlencoded
//main.js,可以设置content-type
import axios from 'axios';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Vue.prototype.$axios = axios;
import qs from 'qs'
let params = { id: 12345 }
let postData = qs.stringify(params);
axios.post('/user', postData)
.then((res) => {
console.log(res);
}).catch((error) => {
console.log(error);
})
-
Content-Type: multipart/form-data
可以同时append参数和文件,上传参考七牛云上传
let formData = new FormData();
formData.append('id','12345');
//formData.append('file',file);
axios.post('/user', formData)
.then((res) => {
console.log(res);
}).catch((error) => {
console.log(error);
})
)
put,delete 这里
axios封装promiose
function axiosPost(url,myParam){
var p = new Promise(function (reslove,reject) {
axios.post({
methods:'post',
url:baseUrl+url,
data:myParam
}).then(function (res) {
reslove(res.data)
}).catch(function (e) {
reject(e)
})
})
return p
}
axios async await
async function f(){
try{
let res = await axiosPost(url,myParam)
}catch (e) {
console.log(e)
}
}