侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

前端  /  管理员 发布于 5年前   390

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错误,并重新跳入登页重新获取tokenaxios.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 qsimport 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)});
 if(config.method=='post'){  config.data=QS.stringify(config.data);//防止post请求参数无法传到后台 }
这句可以直接代替
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';//配置请求头信息。

vue 访问本地json文件的数据测试配置方法
第一步,准备json数据
json文件位置:src/data/data.json
第二步,配置webpack.dev.conf.js 文件
在webpack.dev.config.js 里面添加如下代码:
// 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.HOSTconst 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: ''})

  本地成功请求数据效果:

  

总结

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

您可能感兴趣的文章:

  • vue axios数据请求get、post方法及实例详解
  • vue axios数据请求及vue中使用axios的方法
  • Vue二次封装axios为插件使用详解


  • 上一条:
    vue中实现Monaco Editor自定义提示功能
    下一条:
    基于vue实现圆形菜单栏组件
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 使用 Alpine.js 排序插件对元素进行排序(0个评论)
    • 在js中使用jszip + file-saver实现批量下载OSS文件功能示例(0个评论)
    • 在vue中实现父页面按钮显示子组件中的el-dialog效果(0个评论)
    • 使用mock-server实现模拟接口对接流程步骤(0个评论)
    • vue项目打包程序实现把项目打包成一个exe可执行程序(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-03
    • 2018-04
    • 2018-05
    • 2018-06
    • 2018-09
    • 2018-11
    • 2018-12
    • 2019-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2021-04
    • 2021-05
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客