vue实例的数据请求
数据请求基础知识
- 常见的数据请求类型?
get
post
jsonp
- jsonp的实现原理
- 由于浏览器的安全性限制,不允许
Ajax
访问端口号、域名、协议的数据接口,浏览器认为这种访问不安全 - 可以通过动态创建
script
标签的形式,把script
的src
属性,指向数据接口的地址,因为script
标签不存在跨域限制,这种数据获取方式,称作JSONP(注意:根据JSONP的实现原理,知晓,JSONP只支持GET请求)。 - 具体实现过程:
- 先在客户端定义一个回调方法,预定义对数据的操作;
- 再把这个回调方法的名称,通过URL传参的形式,提交到服务器的数据接口;
- 服务器数据接口组织好要发送给客户端的数据,再拿着客户端传递过来的回调方法名称,拼接出一个调用这个方法的字符串,发送给客户端去解析执行;
- 客户端拿到服务器返回的字符串之后,当作Script脚本去解析执行,这样就能够拿到JSONP的数据了;
- 带大家通过
Node.js
,来手动实现一个JSONP的请求例子;Node
代码
const http = require('http');
// 导入解析 URL 地址的核心模块
const urlModule = require('url');
const server = http.createServer();
// 监听 服务器的 request 请求事件,处理每个请求
server.on('request', (req, res) => {
const url = req.url;
if(url==='/getscript'){
var scriptStr='show()';
res.end(scriptStr);
}else{
res.end("404");
}
});
server.listen(3000, () => {
console.log('server running at http://127.0.0.1:3000');
});
- 前端代码
<script>
function show() {
console.log("ok");
}
</script>
<script src="http://12.0.0.1:3000/getjsonp?"></script>
Ajax
初始化页面发送请求应该尽早(created时发),在mounted时发,页面渲染完毕,初始需假数据和重新加载页面。
vue-resource 实现 get, post, jsonp请求
vue-resource
的配置步骤:- 直接在页面中,通过
script
标签,引入vue-resource
的脚本文件; - 注意:引用的先后顺序是:先引用
vue-resource
的脚本文件
- 直接在页面中,通过
- 发送get请求
getInfo() { // get 方式获取数据
this.$http.get(http://www.liulongbin.top:3005/api/getlunbo').then(res => {
console.log(res.body);
})
}
发现
.then(successCallback,errorCallback)
的回调函数是由promise
封装的,errorCallback
为可选。
- 发送post请求:
postInfo() {
var url = 'http://127.0.0.1:8899/api/post';
// post 方法接收三个参数:
// 参数1: 要请求的URL地址
// 参数2: 要发送的数据对象
// 参数3: 指定post提交的编码类型为 application/x-www-form-urlencoded
this.$http.post(url, { name: 'zs' }, { emulateJSON: true }).then(res => {
console.log(res.body);
});
}
- post请求时,数据对象默认没有表达式(application/x-www-form-urlencoded),有的服务器可能获取不到。
因此第二个参数设置emulate为true - 服务器根地址多次相同,数据库IP地址发生改变,不方便项目维护。以下知识解决该问题。
全局配置数据接口的根域名
- 全局配置
Vue.http.optionsroot='http://www.liulongbin.top:3005/;
- 请求
this.$http.get(api/getlunbo').then(res => {
console.log(res.body);
});
在每次单独发起 http 请求的时候,请求的 url 路径,应该以相对路径开头,前面不能带 / ,否则 不会启用根路径做拼接;
全局配置emulateJSON选项
- 全局配置
Vue.http.options.emulateJSON = true;
- 请求
this.$http.post('api/addproduct', { name: this.name }).then(result => {
if (result.body.status === 0) {
this.getAllList()
this.name = ''
} else {
alert('添加失败!')
}
})
- 发送JSONP请求获取数据:
jsonpInfo() { // JSONP形式从服务器获取数据
var url = 'http://127.0.0.1:8899/api/jsonp';
this.$http.jsonp(url).then(res => {
console.log(res.body);
});
}
axios
的第三包实现数据的请求(Vue.js 2.0 推荐)
- 使用CDN
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
- 使用 npm:
$ npm install axios
- 浏览器支持情况
- 发送get请求
- 无参
axios
.get('https://www.runoob.com/try/ajax/json_demo.json')
.then(response => (this.info = response))
.catch(function (error) { // 请求失败处理
console.log(error);
});
- 有参
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 也可以通过 params 设置参数:
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
- 发送post请求
- 无参
axios
.post('https://www.runoob.com/try/ajax/demo_axios_post.php')
.then(response => (this.info = response));
- 有参
axios.post('/user', {
firstName: 'Fred', // 参数 firstName
lastName: 'Flintstone' // 参数 lastName
})
.then(function (response) {
console.log(response);
});
执行多个并发请求
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));
axios API
可以通过向 axios 传递相关配置来创建请求。
axios(config)
// 发送 POST 请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
// GET 请求远程图片
axios({
method:'get',
url:'http://bit.ly/2mTM3nY',
responseType:'stream'
})
.then(function(response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
axios(url[, config])
// 发送 GET 请求(默认的方法)
axios('/user/12345');
并发
处理开发请求的助手函数:
axios.all(iterable)
axios.spread(callback)