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'即可 } } },
新闻热点
疑难解答
图片精选