vue 使用axios 数据请求第三方插件的使用教程详解

 更新时间:2019年07月05日 14:56:28   作者:*小嘻嘻*  
这篇文章主要介绍了vue 使用axios 数据请求第三方插件的使用 ,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下

axios

基于http客户端的promise,面向浏览器和nodejs

特色

•浏览器端发起XMLHttpRequests请求
•node端发起http请求
•支持Promise API
•监听请求和返回
•转化请求和返回
•取消请求
•自动转化json数据
•客户端支持抵御

安装

使用npm:

$ npm i axiso

为了解决post默认使用的是x-www-from-urlencoded 去请求数据,导致请求参数无法传递到后台,所以还需要安装一个插件QS

$ npm install qs

一个命令全部解决

$ npm install --save axios vue-axios qs

两种方法在vue中使用 axios

方法-:修改原型链

首先在 main.js 中引入 axios

import Axiso from 'axiso'

这时候如果在其它的组件中,是无法使用 axios 命令的。但如果将 axios 改写为 Vue 的原型属性,就能解决这个问题

Vue.prototype.$axios= Axios

 配置好了之后就可以全局使用了

示例:在main.js使用

Get请求:

//发起一个user请求,参数为给定的ID
$axios.get('/user?ID=1234')
.then(function(respone){
  console.log(response);
})
.catch(function(error){
  console.log(error);
});

Post请求

$axios.post('/user', {
  firstName: 'Fred',
  lastName: 'Flintstone'
 })
 .then(function (response) {
  console.log(response);
 })
 .catch(function (error) {
  console.log(error);
 });

为了保证请求的数据正确,可以在main.js配置如下内容:

Axios.defaults.baseURL = 'https://api.example.com';//配置你的接口请求地址
Axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;//配置token,看情况使用
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';//配置请求头信息。

 那么最基本的配置已经完成了,但是还有一个问题,既然是前后端分离,那么肯定避免不了跨域请求数据的问题,接下来就是配置跨域了。

在config/index.js里面的dev里面配置如下代码:

proxyTable: {
   '/api': {
    target: 'http://xxx.xxx.xxx.xxx:8081/',//设置你调用的接口域名和端口号 别忘了加http
    changeOrigin: true,
    pathRewrite: {
     '^/api': '/'//这里理解成用‘/api'代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://xxx.xxx.xxx.xx:8081/user/add',直接写‘/api/user/add'即可
    }
   }

 完整代码:

dev: {
  // Paths
  assetsSubDirectory: 'static',
  assetsPublicPath: '/',
  proxyTable: {
    '/api': {
    target: 'http://xxx.xxx.xxx.xxx:8081/',//设置你调用的接口域名和端口号 别忘了加http
    changeOrigin: true,
    pathRewrite: {
     '^/api': '/'//这里理解成用‘/api'代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我 要调用'http://xxx.xxx.xxx.xxx:8081/user/add',直接写‘/api/user/add'即可
    }
   }
  },

  但是注意了,这只是开发环境(dev)中解决了跨域问题,生产环境中真正部署到服务器上如果是非同源还是存在跨域问题.

axios拦截器的使用

当我们访问某个地址页面时,有时会要求我们重新登录后再访问该页面,也就是身份认证失效了,如token丢失了,或者是token依然存在本地,但是却失效了,所以单单判断本地有没有token值不能解决问题。此时请求时服务器返回的是401错误,授权出错,也就是没有权利访问该页面。

我们可以在发送所有请求之前和操作服务器响应数据之前对这种情况过滤。

// http request 请求拦截器,有token值则配置上token值
axios.interceptors.request.use(
  config => {
    if (token) { // 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了
      config.headers.Authorization = token;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  });
// http response 服务器响应拦截器,这里拦截401错误,并重新跳入登页重新获取token
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 这里写清除token的代码
          router.replace({
            path: 'login',
            query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
          })
      }
    }
    return Promise.reject(error.response.data) 
  });

 安装qs插件后的简化操作

$ npm install qs
import QS from 'qs'
//axios拦截器
// 超时时间
Axios.defaults.timeout = 5000;
// http请求拦截器 请求之前的一些操作
Axios.interceptors.request.use(config => {
 if(config.method=='post'){
  config.data=QS.stringify(config.data);//防止post请求参数无法传到后台
 }
 return config
}, error => {
 Message.error({
  message: '加载超时'
 });
 return Promise.reject(error)
});
// http响应拦截器 请求之后的操作
Axios.interceptors.response.use(data => {
 return data
}, error => {
 Message.error({
  message: '加载失败'
 });
 return Promise.reject(error)
});
<span style="color: rgb(255, 0, 0);"> if(config.method=='post'){
  config.data=QS.stringify(config.data);//防止post请求参数无法传到后台
 }</span><br>这句可以直接代替
<span style="color: rgb(255, 0, 0);">Axios.defaults.baseURL = 'https://api.example.com';//配置你的接口请求地址
Axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;//配置token,看情况使用
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';//配置请求头信息。</span>

<br><span style="font-size: 14pt;">vue 访问本地json文件的数据测试配置方法<br>第一步,准备json数据<br>json文件位置:src/data/data.json<br>第二步,配置webpack.dev.conf.js 文件<br>在webpack.dev.config.js 里面添加如下代码:<br></span>
// webpack.dev.conf.js
// 通过express导入路由
const express = require('express')
const app = express()
var appData = require('../src/data/data.json')
// json卖家数据
var seller = appData.seller
// json商品数据
var goods = appData.goods
// json评论数据
var ratings = appData.ratings
// 编写路由
var apiRoutes = express.Router()
// 所有通过接口相关的api都会通过api这个路由导向到具体的路由
app.use('/api', apiRoutes)
//devServer下写入如下代码:
 before(app) {
   app.get('/api/seller', (req, res) => {
    res.json({
     errno: 0,
     data: seller
    })//接口返回json数据,上面配置的数据seller就赋值给data请求后调用
   }),
    app.get('/api/goods', (req, res) => {
     res.json({
      errno: 0,
      data: goods
     })
    }),
    app.get('/api/ratings', (req, res) => {
     res.json({
      errno: 0,
      data: ratings
     })
    })
  }

  按照如上配置就大功告成了,webpack.dev.config.js 完整代码如下:

'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')
// webpack.dev.conf.js
// 通过express导入路由
const express = require('express')
const app = express()
var appData = require('../src/data/data.json')
// json卖家数据
var seller = appData.seller
// json商品数据
var goods = appData.goods
// json评论数据
var ratings = appData.ratings
// 编写路由
var apiRoutes = express.Router()
// 所有通过接口相关的api都会通过api这个路由导向到具体的路由
app.use('/api', apiRoutes)
const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)
const devWebpackConfig = merge(baseWebpackConfig, {
 module: {
  rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
 },
 // cheap-module-eval-source-map is faster for development
 devtool: config.dev.devtool,
 // these devServer options should be customized in /config/index.js
 devServer: {
  clientLogLevel: 'warning',
  historyApiFallback: {
   rewrites: [
    { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
   ],
  },
  hot: true,
  contentBase: false, // since we use CopyWebpackPlugin.
  compress: true,
  host: HOST || config.dev.host,
  port: PORT || config.dev.port,
  open: config.dev.autoOpenBrowser,
  overlay: config.dev.errorOverlay
   ? { warnings: false, errors: true }
   : false,
  publicPath: config.dev.assetsPublicPath,
  proxy: config.dev.proxyTable,
  quiet: true, // necessary for FriendlyErrorsPlugin
  watchOptions: {
   poll: config.dev.poll,
  },
  before(app) {
   app.get('/api/seller', (req, res) => {
    res.json({
     errno: 0,
     data: seller
    })//接口返回json数据,上面配置的数据seller就赋值给data请求后调用
   }),
    app.get('/api/goods', (req, res) => {
     res.json({
      errno: 0,
      data: goods
     })
    }),
    app.get('/api/ratings', (req, res) => {
     res.json({
      errno: 0,
      data: ratings
     })
    })
  }
 },
 plugins: [
  new webpack.DefinePlugin({
   'process.env': require('../config/dev.env')
  }),
  new webpack.HotModuleReplacementPlugin(),
  new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
  new webpack.NoEmitOnErrorsPlugin(),
  // https://github.com/ampedandwired/html-webpack-plugin
  new HtmlWebpackPlugin({
   filename: 'index.html',
   template: 'index.html',
   inject: true
  }),
  // copy custom static assets
  new CopyWebpackPlugin([
   {
    from: path.resolve(__dirname, '../static'),
    to: config.dev.assetsSubDirectory,
    ignore: ['.*']
   }
  ])
 ]
})
module.exports = new Promise((resolve, reject) => {
 portfinder.basePort = process.env.PORT || config.dev.port
 portfinder.getPort((err, port) => {
  if (err) {
   reject(err)
  } else {
   // publish the new Port, necessary for e2e tests
   process.env.PORT = port
   // add port to devServer config
   devWebpackConfig.devServer.port = port
   // Add FriendlyErrorsPlugin
   devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
    compilationSuccessInfo: {
     messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
    },
    onErrors: config.dev.notifyOnErrors
    ? utils.createNotifierCallback()
    : undefined
   }))
   resolve(devWebpackConfig)
  }
 })
})

  main.js完整代码如下:

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import Axios from 'axios'
import QS from 'qs'
Vue.prototype.$axios=Axios //原型链配置
Vue.config.productionTip = false
//axios拦截器
// 超时时间
Axios.defaults.timeout = 5000;
// http请求拦截器
Axios.interceptors.request.use(config => {
 if(config.method=='post'){
  config.data=QS.stringify(config.data);//防止post请求参数无法传到后台
 }
 return config
}, error => {
 Message.error({
  message: '加载超时'
 });
 return Promise.reject(error)
});
// http响应拦截器
Axios.interceptors.response.use(data => {
 return data
}, error => {
 Message.error({
  message: '加载失败'
 });
 return Promise.reject(error)
});
// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
 // 当被绑定的元素插入到 DOM 中时……
 inserted: function (el) {
  // 聚焦元素
  el.focus()
 }
})
/* eslint-disable no-new */
new Vue({
 el: '#app',
 router,
 components: { App },
 template: '<App/>'
})

  本地成功请求数据效果:

<span style="font-size: 14pt;"> </span> 

总结

以上所述是小编给大家介绍的vue 使用axios 数据请求第三方插件的使用教程详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

  • 详解vue slot插槽的使用方法

    详解vue slot插槽的使用方法

    本篇文章主要介绍了详解vue slot插槽的使用方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06
  • Vue3中refs使用方法举例

    Vue3中refs使用方法举例

    在Vue中Refs是对DOM元素或已安装到DOM的其他组件实例的引用,下面这篇文章主要给大家介绍了关于Vue3中refs使用的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2024-08-08
  • Vue组合式API如何正确解构props不会丢失响应性

    Vue组合式API如何正确解构props不会丢失响应性

    响应式 API 赋予了组合式 API 一大坨可能性的同时,代码精简,虽然但是,我们应该意识到响应性的某些陷阱,比如丢失响应性,在本文中,我们将学习如何正确解构 Vue 组件的 props,使得 props 不会丢失响应性
    2024-01-01
  • vue使用Office Web实现线上文件预览

    vue使用Office Web实现线上文件预览

    这篇文章主要为大家介绍了vue使用微软的开发接口Office Web,实现线上文件预览,预览word,excel,pptx,pdf文件,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-07-07
  • vue的安装及element组件的安装方法

    vue的安装及element组件的安装方法

    下面小编就为大家分享一篇vue的安装及element组件的安装,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-03-03
  • 最新Vue过滤器介绍及使用方法

    最新Vue过滤器介绍及使用方法

    过滤器是vue为开发者提供的功能,常用于文本的格式化,过滤器应该被添加在JavaScrip表达式的尾部,由“管道符”进行调用,这篇文章通过案例给大家讲解Vue过滤器介绍及使用方法,需要的朋友参考下吧
    2022-11-11
  • Vue单页面应用做预渲染的方法实例

    Vue单页面应用做预渲染的方法实例

    vue是一个单页面的应用,这导致一些爬虫和百度无法搜索到,如果你想针对你应用的其中某些页面进行SEO优化,让他们可以被爬虫和百度搜索到,你可以进行预渲染操作,下面这篇文章主要给大家介绍了关于Vue单页面应用做预渲染的相关资料,需要的朋友可以参考下
    2021-10-10
  • 使用vue for时为什么要key【推荐】

    使用vue for时为什么要key【推荐】

    很多朋友不明白在使用vue for时为什么要key,key的作用有哪些,在文中给大家详细介绍,需要的朋友可以参考下
    2019-07-07
  • element-ui中导航组件menu的一个属性:default-active说明

    element-ui中导航组件menu的一个属性:default-active说明

    这篇文章主要介绍了element-ui中导航组件menu的一个属性:default-active说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-05-05
  • 详解Vue3 SFC 和 TSX 方式调用子组件中的函数

    详解Vue3 SFC 和 TSX 方式调用子组件中的函数

    在使用 .vue 定义的组件中,setup 中提供了 defineExpose() 方法,该方法可以将组件内部的方法暴露给父组件,这篇文章主要介绍了Vue3 SFC 和 TSX 方式调用子组件中的函数,需要的朋友可以参考下
    2022-10-10

最新评论