赞
踩
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
支持浏览器和node.js
支持promise
能拦截请求和响应
能转换请求和响应数据
能取消请求
自动转换JSON数据
浏览器端支持防止CSRF(跨站请求伪造)
npm安装
$ npm install axios
bower安装
$ bower install axios
通过cdn引入
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
- import Axios from "axios"
- Vue.prototype.$axios = Axios
- mounted(){
- this.$axios.get("http://www.wwtliu.com/sxtstu/blueberrypai/getChengpinInfo.php")
- .then(res => {
- console.log(res.data);
- })
- .catch(error => {
- console.log(error);
- })
- }
上面的请求也可以这样写:
- axios.get('/user', {
- params: {
- ID: 12345
- }
- })
- .then(function (response) {
- console.log(response);
- })
- .catch(function (error) {
- console.log(error);
- });
- axios.post('/user', {
- firstName: 'Fred',
- lastName: 'Flintstone'
- })
- .then(function (response) {
- console.log(response);
- })
- .catch(function (error) {
- console.log(error);
- });
- function getUserAccount() {
- return axios.get('/user/12345');
- }
-
- function getUserPermissions() {
- return axios.get('/user/12345/permissions');
- }
-
- axios.all([getUserAccount(), getUserPermissions()])
- .then(axios.spread(function (acct, perms) {
- // 两个请求现在都执行完成
- }));
response由以下几部分信息组成
- {
- // 服务端返回的数据
- data: {},
-
- // 服务端返回的状态码
- status: 200,
-
- // 服务端返回的状态信息
- statusText: 'OK',
-
- // 响应头
- // 所有的响应头名称都是小写
- headers: {},
-
- // axios请求配置
- config: {},
-
- // 请求
- request: {}
- }

为方便起见,为所有支持的请求方法提供了别名
- axios.request(config)
- axios.get(url[, config])
- axios.delete(url[, config])
- axios.head(url[, config])
- axios.post(url[, data[, config]])
- axios.put(url[, data[, config]])
- axios.patch(url[, data[, config]])
then接收以下响应信息
- axios.get('/user/12345')
- .then(function(response) {
- console.log(response.data);
- console.log(response.status);
- console.log(response.statusText);
- console.log(response.headers);
- console.log(response.config);
- });
在请求或响应被 then 或 catch 处理前拦截它们。
- // 添加请求拦截器
- axios.interceptors.request.use(function (config) {
- // 在发送请求之前做些什么
- return config;
- }, function (error) {
- // 对请求错误做些什么
- return Promise.reject(error);
- });
-
- // 添加响应拦截器
- axios.interceptors.response.use(function (response) {
- // 对响应数据做点什么
- return response;
- }, function (error) {
- // 对响应错误做点什么
- return Promise.reject(error);
- });
-

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。