Vue 前后端交互
异步调用
- 异步效果 : 事件函数 Ajax 定时任务
- 多次异步调用依赖
- 多次调用异步, 结果顺序不确定, 如果需要固定顺序, 必须使用嵌套
Promise 概述
Promise 是异步编程的一种解决方案 , 从语法上讲 Promise 是一个对象 , 从它可以获取到异步操作的消息;
- 可以避免多层异步调用嵌套问题
- Promise 对象提供了简洁的 api 可以轻松控制异步操作
// resolve 正确的回调 reject 错误的回调
var p = new Promise(function (resolve, reject) {
var flag = true
setTimeout(function () {
if (flag) {
resolve('success...')
} else {
reject('error...')
}
}, 2000)
})
// then 方法接收 resolve 和 reject 的返回
p.then(function (res) {
console.log(res)
}, function (err) {
console.log(err)
})
Promise 封装原生 Ajax
query(url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest()
xhr.onload = function () {
if (xhr.status === 200) {
resolve(xhr.responseText)
} else {
reject('error...')
}
}
xhr.open('get', url)
xhr.send(null)
})
}
// 多重接口调用
query('http://localhost:3000/data')
.then(function(res) {
console.log(res)
return query('http://localhost:3000/data1')
})
.then(function (res) {
console.log(res)
return query('http://localhost:3000/data2')
})
.then(function (res) {
console.log(res)
})
then 参数中的返回值
返回 Promise 实例对象
- 返回该实例对象会调用下一个then
返回普通值
- 返回的普通值会直接传递写一个then , 通过 then 参数中函数的参数接收该值
query('http://localhost:3000/data')
.then(function(res) {
return res
})
.then(function(data){
console.log(data)
})
Promise 常用 API
实例方法
- p.then() 得到异步任务的正确结果
- p.catch() 获取异步任务的错误结果
- p.finally() 成功与否都会执行(尚且不是正确标准)
var query = function () {
return new Promise(function (resolve, reject){
setTimeout(function () {
// resolve('success')
reject('error')
}, 500)
})
}
query()
.then(function(data) {
console.log(data)
})
.catch(function(data) {
console.log(data)
})
.finally(function (data) {
console.log('finally...')
})
对象方法
var p1 = query('http://localhost:3000/a1')
var p2 = query('http://localhost:3000/a2')
var p3 = query('http://localhost:3000/a3')
-
Promise.all()并发处理多个异步任务, 所有任务都执行完成才能得到结果-
Promise.all([p1, p2, p3]).then(function (result) { console.log(result) })
-
-
Promise.race()并发处理多个异步任务, 只要有一个任务完成就能得到结果-
Promise.race([p1, p2, p3]).then(function (result) { console.log(result) })
-
fetch 接口调用 用法
get delete 使用方法
fetch('http://localhost:3000/books/3', {
// 指定请求方式 get,delete 方法在URL直接拼接参数即可
method: 'get'
})
.then(function(data) {
// text() 返回 Promise 对象
return data.text() // 返回文本对象
return data.json() // 返回json对象
})
.then(function (res) {
console.log(res)
})
post put 使用方法
// 表单提交
fetch('http://localhost:3000/books', {
method: 'post',
body: 'uname=zs&age=23',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
// json 提交
fetch('https://www.fungoweb.com/api/portal/games/content/game/queryHomePage', {
method: 'post',
body: JSON.stringify({
page: 1
}),
headers: {
'Content-Type': 'application/json;charset=utf8'
}
})
接口调用 axios 用法
axios (https://www.kancloud.cn/yunye/axios/234845) 是一个基于 promise 的 HTTP 库,
- 支持浏览器和Node
- 支持 Promise
- 可以拦截请求响应
- 自动转换 JSON 数据
axios.get('http://baidu.com')
.then(function (result) {
console.log(result.data)
})
常用 API get delete传参方式
-
restfull 传参
-
axios.get('http://baidu.com/123')
-
-
URL 传参
-
axios.get('http://baidu.com?id=123')
-
-
params 传参; URL拼接的另一种形式
-
axios.get('http://baidu.com', { params: { id: 1 } })
-
常用 API post put 传参方式
-
表单传输
-
var params = new URLSearchParams() params.append('page', 1) params.append('limie', 10) axios.post('https://www.post', params)
-
-
json 传输
-
axios.post('https://www.post', { page: 1, limit: 10 })
-
axios 响应结果
data: 实际响应回来的数据
headers: 响应头信息
status: 响应状态码
statusText: 响应状态信息

axios 全局配置
// 配置全局 基准 url 以后的请求就不需要指定了
axios.defaults.baseURL = 'http://localhost:3000'
// 配置全局 发送请求时的默认请求头
axios.defaults.headers['mytoken'] = 'hello axios'
// 配置请求 超时时间 ms
axios.default.timeout = 3000
axios 拦截器
请求拦截器 : 在请求发送之前设置一些信息
// 发送请求之前设置
axios.interceptors.request.use(function (config) {
console.log(config)
config.headers.mytoken = 'hello axios'
// 必须把这个 config return 出去
return config
}, function (err) {
console.log(err)
})
// 下面可以继续正常发送请求
响应拦截器 : 在获取服务器数据之前做一些加工
// 发送请求之前
axios.interceptors.response.use(function (res) {
console.log(res) // 与请求时返回的响应对象是一样的, 但是可以在这里进行一些处理
return res
})
async/await 基本用法
async 关键字用于函数上 (async 函数的返回值是Promise实例对象)
await 关键字用于 async 函数当中 (await 可以得到异步的结果)
async function query() {
// 如果是多个请求有依赖的话, 会等到第一个请求返回结果后才去调用第二个请求
var result = await axios.get('http://localhost:3000/json')
var result = await axios.get('http://localhost:3000/json' + result.data.info)
return result
}
query().then(function (res) {
console.log(res)
})

浙公网安备 33010602011771号