vue里面有ajax,vue中的ajax请求

一、fetch

原生js新增 用于请求数据

fetch(url,{

headers:{

"token":localStorage.getItem('token'),

"content-type":"apllication-xxx-urlencoded"

},

method:"GET/POST",

data:{

}

}).then(function(res){

//设置返回格式 text() arrayBuffer() blob() formData()

return res.json()

}).then(res=>{

//res 才是请求的结果 格式化之后(什么格式取决于 第一个 then 返回的处理方法)

})

二、axios

get请求方式

//地址栏传数据

axios.get('url?userName=xxx').then(res=>{}).catch(err=>{})

axios.get(url,{

params:{

userName:"xxx"

},

headers:{

}

}).then(res=>{}).catch(err=>{})

post请求

axios.post('/user', {

firstName: 'Fred',

lastName: 'Flintstone'

})

.then(function (res) {

console.log(res);

})

.catch(function (error) {

console.log(error);

});

完整请求

axios({

method: 'post',

url: '/user/12345',

headers:{

},

data: {

firstName: 'Fred',

lastName: 'Flintstone'

}

}).then().catch()

创实例

可以对所有的请求,做一些初始化配置,配置是作用域所有的用实例的请求

const instance = axios.create({

baseURL: 'https://some-domain.com/api/',

headers: {'X-Custom-Header': 'foobar'}

});

//instance.get("/gateway", { params:{ }}).then(res=>{})

//instance.post("/gateway", {data:{ }}).then(res=>{})

axios拦截器

拦截请求响应

// 添加 请求 拦截器

axios.interceptors.request.use(function (config) {

// 可以在请求发送之前做一些事情 config 请求信息 config.headers

return config;

}, function (error) {

// 出错了 走这里

return Promise.reject(error);

});

// 添加相应拦截

axios.interceptors.response.use(function (response) {

// 在2xx范围内的任何状态代码都会触发此函数(请求成功触发)

// 在相应数据 发送到 ajax之前,可以在这里拦截

return response;

}, function (error) {

// 任何超出2xx范围的状态码都会触发此函数(请求失败触发)

// 响应失败执行

return Promise.reject(error);

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值