axios快速入门

现在的ajax技术已经很好了,但是vue.js中axios方法是vue特有的,这里简单介绍一下。

axios中文文档:

https://www.kancloud.cn/yunye/axios/234845

这边博客写的不错:https://www.jianshu.com/p/df464b26ae58

一、简介

axios 是一个基于 Promise 的 HTTP 客户端,专门为浏览器和 node.js 服务

特点

二、快速入门

1、安装axios

使用npm  

cnpm install axios -save

2、main.js引入、挂载

import Axios from 'axios' //引入axios

Vue.prototype.$axios = Axios; //挂载在vue原型上
//设置全局的 axios 配置,根据需要配置相关参数,参考axios文档
Axios.defaults.baseURL = 'http://www.baidu.com/jsee';
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// 添加请求拦截器
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);
  });

3、基本使用

//执行get请求

this.$axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

//执行post请求

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

返回中response:

注意点:

axios的post请求默认的请求参数格式是form-data

form-data;  ?id=2&name='李四'

x-www-form-urlencoded: {id:2,name:'李四'}

所以,josn数据格式在传输中需要qs序列化参数,否则后台是接收不到数据的。

import Qs from 'qs' //序列化的函数

this.$axios.post('/get_IndexNews_Recommended.do',
                Qs.stringify({ //序列化参数
                    type: "101"
                })
                )  .then(function(response) {
                        console.log(response);
                    })
                    .catch(function(error) {
                        console.log(error);
                    });

三、axios跨域

解决方案:

步骤:

1、修改接口前置地址

Axios.defaults.baseURL = 'http://www.baidu.com/jsee'; 改为 Axios.defaults.baseURL = '/api';

2、修改config文件夹下的index.js文件,在proxyTable中加上如下代码:

3、重启服务,测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值