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)
});

  

 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.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/>'
})

  本地成功请求数据效果:

 
												

vue 使用axios 数据请求第三方插件的使用的更多相关文章

  1. day 74 vue 2 axios数据请求 以及组件的学习

    前情提要:   vue 学习二: 一: 通过axios实现数据请求 1:json数据语法 json数据对象类似于JavaScript中的对象,但是它的键对应的值里面是没有函数方法的,值可以是普通变量, ...

  2. VUE - 使用axios数据请求时数据绑定时 报错 TypeError: Cannot set property 'xxxx' of undefined 的解决办法

     created() {     var that=this     axios.get('http://jsonplaceholder.typicode.com/todos')     .then( ...

  3. Vue 使用 axios post请求后台数据时 404

    今天遇到Vue 使用 axios post请求后台数据时 404 使用postman 就能获取到 网上找了大半天 终于找到了解决方法,传送门:https://www.jianshu.com/p/b10 ...

  4. 02 Vue之vue对象属性功能&axios数据请求实现

    1.过滤器的声明和使用 过滤器,就是vue允许开发者自定义的文本格式化函数,可以使用在两个地方:输出内容和操作数据中. 定义过滤器的方式有两种. 1 使用Vue.filter()进行全局定义 2 在v ...

  5. vue axios数据请求get、post方法的使用

    我们常用的有get方法以及post方法,下面简单的介绍一下这两种请求方法 vue中使用axios方法我们先安装axios这个方法 npm install --save axios 安装之后采用按需引入 ...

  6. vue axios 数据请求实现

    1.安装nginx npm install axios --save-dev cnpm install axios --save-dev 使用淘宝镜像 保存依赖文件到本地 装好了.packjson.j ...

  7. 运行命令区分webpack环境,以及axios数据请求的封装

    在开发环境和线上环境时,由于环境的不同,有时候需要修改一定的代码,可以通过配置webpack环境来减少对代码的修改:另外,有时候去看别人的代码,你可能都找不到他的数据请求在什么位置,最近在做一个vue ...

  8. vue使用axios发送请求,都会发送两次请求

    vue 使用axios,每次的请求都会发送两次,第一次的请求头为options CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sha ...

  9. vue中axios 配置请求拦截功能 及请求方式如何封装

    main.js 中: import axios from '................/axios' axios.js 中: //axios.js import Vue from 'vue' i ...

随机推荐

  1. Phonegap 自定义插件

    一.PhoneGap中js与Java之间相互调用分为同步和异步两种方式 1.同步:js调用Java类的方法,然后Java类的方法直接返回一个值给js端 2.异步:js调用Java类的方法,Java类的 ...

  2. redis Linux 、Windows ubuntu 下的安装

    Redis 安装 2018-07-05 Window 下安装 下载地址:https://github.com/MSOpenTech/redis/releases. Redis 支持 32 位和 64 ...

  3. 【python】函数名存在变量中

    变量函数:意思就是将函数名存在变量中,然后根据变量值动态的调用需要的函数. LOGIN = 'xxxx' PASSWD = "xxx" URL = 'xxxxx' def hand ...

  4. SouthidcEditor编辑器如何支持上传png图片

    SouthidcEditor编辑器如何支持上传png图片? asp网站一般都是用的南方数据SouthidcEditor编辑器,可是这个编辑器上传图片功能不能上传png类型的图片,那怎么办?我(红蜘蛛网 ...

  5. Makefile编写 三 伪目标的作用

    本节我们讨论一个Makefile中的一个重要的特殊目标:伪目标. 伪目标是这样一个目标:它不代表一个真正的文件名,在执行make时可以指定这个目标来执行其所在规则定义的命令,有时我们也可以将一个伪目标 ...

  6. TS流解析 二 *****

    1.TS格式介绍 TS:全称为MPEG2-TS.TS即"Transport Stream"的缩写.它是分包发送的,每一个包长为188字节(还有192和204个字节的包).包的结构为 ...

  7. bzoj 3059: 归途与征程

    Description 给出一个长度为N的由小写字母’a’~’z’和’*’组成的字符串A,一个长度为M的仅由小写字母’a’~’z’组成的字符串B.一个’*’可以匹配任意多个字符(包括0个).求在B的所 ...

  8. Bootstrap-Plugin:按钮(Button)插件

    ylbtech-Bootstrap-Plugin:按钮(Button)插件 1.返回顶部 1. Bootstrap 按钮(Button)插件 按钮(Button)在 Bootstrap 按钮 一章中介 ...

  9. 20181124_webAPI基础01_创建一个基础的WebAPI项目

    1. webApi属于RESTful架构风格, 而RESTful风格, 是以资源为视角来描述服务的 2. 创建webAPI项目 3. 选择webAPI, 然后mvc会自动引用 4. 点击确定, 就创建 ...

  10. win10中打开SQL Server配置管理器方法

    使用 Windows10 访问 SQL Server 配置管理器 因为 SQL Server 配置管理器是 Microsoft 管理控制台程序的一个管理单元而不是单独的程序,所以,当运行 Window ...