QQ咨询 官方微信

添加微信好友

官方小程序

百度小程序

微信小程序

头条小程序

关于我们

vue教程

vue请求接口获取数据的实现及跨域问题

 shitouadmin  2023-06-24 23:22:33
本文基于vue-cli3。

一、通过api接口获取数据
在vuejs中请求接口,大体分为两种方式:vue-source和axios。它们都是经过良好封装的http请求插件。

下文将简单介绍一下使用方法。

1. vue-source

安装
首先,安装该插件:
  1. npm install vue-source --save 
然后,在项目src/main.js中,通过全局方法Vue.use()使用该插件:
  1. import VueSource from 'vue-source' 
  2. Vue.use(VueSource) 
使用

在data中定义好接口和接收的数据类型,然后,调用this.$http.get()函数进行get请求即可,代码如下:
  1. data () { 
  2.   return { 
  3.     apiUrl: 'https://xxxxx'
  4.     users: [] 
  5.   } 
  6. }, 
  7. methods: { 
  8. }, 
  9. created () { 
  10.   this.$http.get(this.apiUrl).then((response) => { 
  11.     console.log(response) 
  12.   }, (error) => { 
  13.     console.log('error:', error) 
  14.   }) 

代码解释:$http.get().then()是get函数请求返回后才调用的函数。then()函数的中两个参数是匿名函数。上述代码使用了ES6新增了箭头函数(即参数指向函数),也可以写成以下形式:
  1. this.$http.get(this.apiUrl).then(function (response) { 
  2.   console.log(response) 
  3. }, function (error) { 
  4.   console.log('error:', error) 
  5. }) 
2. axios
安装
  1. npm install axios 
使用
axios库的主要请求函数有:
  1. axios.request(config) 
  2. axios.get(url[, config])  // 表示 axios.get(url, config) 和 axios.get(url) 都被允许 
  3. axios.delete(url[, config]) 
  4. axios.head(url[, config]) 
  5. axios.post(url[, data[, config]]) 
  6. axios.put(url[, data[, config]]) 
  7. axios.patch(url[, data[, config]]) 

config对象的详细属性、请求的后续then()/catch()操作、配置的默认值/defaults等等,见 Axios 中文说明。
示例:
  1. // src/api/api.js 
  2. import axios from 'axios' 
  3.  
  4. // 允许跨域携带cookie 
  5. // axios.defaults.withCredentials = true; 
  6.  
  7. export const uploadelf = () => { 
  8.     return axios.request({ 
  9.         method: 'post'
  10.         url: 'http://xxxxx.xxx/api/uploadelf' 
  11.     }) 
  12.  
  13. export const start = () => { 
  14.     return axios.request({ 
  15.         method: 'get'
  16.         url: 'http://xxxxx.xxx/api/start' 
  17.     }) 
  18.  
  19. export const getDisassemble = (funName = 'main') => { 
  20.     return axios.request({ 
  21.         method: 'post'
  22.         url: 'http://xxxxx.xxx/api/disassemble'
  23.         data: { 
  24.             funName 
  25.         } 
  26.     }) 
其中,每个函数返回一个调用请求后的对象,相当于设计模式中的工厂方法。
如此封装的好处是,用户使用时,并不需要知道某个请求的请求url和请求方式。
当你需要在其它模块中进行相应的请求时,只需要import导入api.js中相应的函数变量并调用即可,如:
  1. // src/view/main.vue 
  2.  
  3. ... 
  4.  
  5. <script> 
  6. // 导入相应的请求函数 
  7. import {uploadelf, start, getDisassemble} from '../api/api' 
  8.  
  9. export default { 
  10.   data() { 
  11.     return { 
  12.       assemb: [] 
  13.     } 
  14.   }, 
  15.   methods: { 
  16.     click_uploadelf() { 
  17.       // 调用该工厂方法进行请求返回一个对象,再通过对象的then(), catch()方法进行后续操作 
  18.       uploadelf().then(resp => { 
  19.         console.log('uploadelf --->', resp.data); 
  20.       }).catch(error => { 
  21.         console.log(error); 
  22.       }); 
  23.     }, 
  24.     click_start() { 
  25.       start().then(resp => { 
  26.         console.log('start --->', resp.data); 
  27.       }).catch(error => { 
  28.         console.log(error); 
  29.       }); 
  30.     }, 
  31.     click_getDisassemble() { 
  32.       getDisassemble('main').then(resp => { 
  33.         console.log('getDisassemble --->', resp.data); 
  34.         this.assemb = resp.data.message; 
  35.       }).catch(error => { 
  36.         console.log(error); 
  37.       }); 
  38.     } 
  39.   } 
  40. </script> 
补充

js的请求属于异步操作(不需要等请求完成,函数直接执行结束)。所以,需要通过回调函数来实现请求完成的后续操作。

axios主要利用ES6 Promise来实现异步请求的后续操作。

同时,异步请求会导致请求并行的情况。多个请求之前不能太接近。

二、跨域问题
1.问题
如果是本机localhost:8000测试,可能会出现跨域问题

2.补充
当两个域具有相同的协议(如http), 相同的端口(如80),相同的域名如www.baidu.com,那么我们就可以认为它们是在相同的域中(协议,域名,端口都必须相同)。

跨域,就是指协议、域名、端口其中一个或多个不一致的情况下,从当前域去访问另一个域。

出于安全考虑(防止跨域攻击 XSS、CSRF),浏览器会禁止跨域的请求访问。其实,同源策略是一种约定,它也是浏览器最核心也最基本的安全功能。

3.解决
跨域问题解决有很多方式,以下主要讲两种。

CROS(跨域资源共享)

前端Vue,设置axios允许跨域带cookie(默认不带cookie),如下:
  1. // axios全局配置,允许跨域带cookie 
  2. axios.defaults.withCredentials = true

后端:

跨域请求后的响应头中需要设置:
  1. Access-Control-Allow-Origin为发起请求的主机地址。 
  2. Access-Control-Allow-Credentials,当它被设置为true时,允许跨域带cookie,但此时Access-Control-Allow-Origin不能为通配符*。 
  3. Access-Control-Allow-Headers,设置跨域请求允许的请求头。 
  4. Access-Control-Allow-Methods,设置跨域请求允许的请求方式。 

Vue代理

vue-cli自带代理功能,由node服务器实现。

在项目根目录下新增vue.config.js项目配置文件,然后配置代理:

  1. // 修改配置后一定要 重新npm run serve !!! 
  2. module.exports = { 
  3.     devServer: { 
  4.         // vue项目启动时的ip地址和端口 
  5.         host: 'localhost'
  6.         port: 8000, 
  7.         proxy: { 
  8.             // 匹配所有以 /api 开头的url 
  9.             '/api': { 
  10.                 // 请求的目标主机 
  11.                 target: 'http://dev3.airdb.io:8080'
  12.                 changeOrigin: true
  13.                 ws: true 
  14.                 // 这样重写会把路径中 /api 消去 
  15.                 // pathRewrite: { 
  16.                 //   '^/api': '/api' 
  17.                 // } 
  18.             } 
  19.         } 
  20.     } 
设置代理后,本地nodejs服务器会将目标主机的url代理到vue项目的url。

如:访问http://dev3.airdb.io:8080,会转变成访问http://localhost:8080,再由http://localhost:8080转发请求到http://dev3.airdb.io:8080。
这样,就成了同域请求,浏览器不会进行限制。但实际上,还是请求了目标主机,只是欺骗了浏览器。
由于Vue代理需要利用node服务器,所以只适用于本地npm run serve调试时。
当项目部署到服务器时,可以使用CROS方式、nginx反向代理等方式。
nginx反向代理
只需要在nginx.conf配置文件的vue项目对应的server中,添加:
  1. # 匹配vue项目中所有以/api开头的请求url 
  2. location /api { 
  3.     include  uwsgi_params; 
  4.     proxy_pass   http://0.0.0.0:8081; # 要代理访问的后端url 

完整示例如下:
  1. server { 
  2.     listen       8000; 
  3.     listen       80; 
  4.     server_name  _; 
  5.     root         /pathto/vue_project/; 
  6.  
  7.     # Load configuration files for the default server block. 
  8.     include /etc/nginx/default.d/*.conf; 
  9.  
  10.     location / { 
  11.         index index.html; 
  12.     } 
  13.  
  14.     error_page 404 /404.html; 
  15.         location = /40x.html { 
  16.     } 
  17.  
  18.     error_page 500 502 503 504 /50x.html; 
  19.         location = /50x.html { 
  20.     } 
  21.  
  22.     location /api { 
  23.         include  uwsgi_params; 
  24.         proxy_pass   http://0.0.0.0:8081; 
  25.     } 


¥ 打赏
×
如果您觉得文章帮助了您就打赏一下吧
非常感谢你的打赏,我们将继续分享更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

本文《vue请求接口获取数据的实现及跨域问题》发布于石头博客文章,作者:shitouadmin,如若转载,请注明出处:https://www.pweb123.com/frame/vue/964.html,否则禁止转载,谢谢配合!

文章点评

我来说两句 已有0条评论
点击图片更换

添加微信好友

添加微信好友

微信小程序

百度小程序