vue数据请求
使用vue框架后,数据请求基本不会使用原生Ajax。
因为Ajax不符合模块化思想。
两个数据请求方案[ 二选一 ]
- 第三方模块: axios
Vue中可以统一对axios进行挂载
Vue.prototype.$http = axios
- 原生js提供: fetch
axios
- axios 是一个基于promise的HTTP库,可以用在浏览器和 node.js 中。
- axios的返回值是一个封装对象,可以提高安全性
- axios使用
- 模拟数据请求
- 后端接口请求
- get
- post
- json
- 表单提交
- puta
- delete
- baseURL 连接后端接口的地址
例如axios.defaults.baseURL = 'http://xxxxx'
axios -> get请求
put,delete请求和get请求一致
axios.get(url,options)
axios({
url:'/',
method:'get' //默认就是get 可以省略
params:{ //get请求携带参数使用params
a,
b
}
}).then(res => console.log(res))
.catch(err => console.log(err))
axios -> post请求
- 使用application/json来发送请求
axios({
// 发送用户名密码请求
url: '/users',
method: 'POST',
data: { //post请求携带参数使用data
username,
password,
token: ''
}
}).then(res => console.log(res))
.catch(err => console.log(err))
- 使用application/x-www-form-urlencoded来发送请求
// 同样发送用户名密码
const p = new URLSearchParams() // 得到数据参数携带对象
// 使用append方法来进行数据的传输
p.append('username', username)
p.append('password', password)
axios({
url: '/users',
method: 'POST',
data: p //携带数据使用依旧data
}).then(res => console.log(res))
.catch(err => console.log(err))
fetch
- 原生JS提供,可以说Ajax封装版本,用起来简易
- 符合模块化思想
- 在浏览器中呈现的fetch字样
- fetch也是promise
- fetch返回值是没有进过封装的,安全度比axios要低
方法:fetch( url,options )
fetch -> get请求
fetch('/',{ //fetch的参数只能连接在地址后面
method:'GET'
}).then( data => data.json() ) //数据格式化 json() text() blob() 二进制格式化
.then( res => console.log(res)) //res就是得到的真正的数据
.catch( err => console.log(err))
fetch -> post请求
// application/x-www-form-urlencoded 提交
post () {
fetch(`/users`,{
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交
}),
body: new URLSearchParams([["username", 'xiaoming'],["password", 123]]).toString() // 这里是请求对象
})
.then( data => data.json() ) // 数据格式化 json() text() blob() 二进制格式化
.then( res => console.log( res )) // res就是得到的真正的数据
.catch( err => console.log( err ))
}
//application/json 提交
postJSON () {
fetch(`${ baseURL }/users`, {
method: 'POST', // or 'PUT'
body: JSON.stringify({
username: '小明',
password: 123
}), // data can be `string` or {object}!
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}