vue-cli项目中使用axios

前言

前后端数据交互中,我们使用最多的就是jQuey中的ajax进行数据交互,但是随着大前端日益的扩大,越来越多的库和框架也渐渐的出现在前端开发人员面前,而本编博客需要介绍的就是在vue-cli项目中使用另一个库代替jQuey中的ajax,那就是axios,Vue更新到2.0之后宣告不再对vue-resource更新,推荐使用axios,axios是一个用于客户端与服务器通信的组件,axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端javaScript工具。通俗来说可以实现客户端请求服务器端提供的服务获得数据。

本章目标

  • 学会使用axios中的相关内容

axios简介

特点

  • 从浏览器中创建 XMLHttpRequest
  • 从 node.js 发出 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换JSON数据
  • 客户端支持防止 CSRF/XSRF

浏览器兼容性

依赖办法

nmp依赖方法

$ npm install axios
$ cnpm install axios //taobao

yarn依赖方法

$ yarn add axios

cdn依赖方法

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

axios资源:https://github.com/axios/axios

项目搭建

为了方便和使用axios,我们这里需要使用后台,在这里后台我使用的是ssm框架,不会搭建的园友可以查看我的这篇博客浅谈IDEA集成SSM框架(SpringMVC+Spring+MyBatis),这篇博客写的真是非常详细,博主良心推荐,包教包会,全网最好,没有之一。那么开始搭建项目吧!

数据库

sql脚本

create table book(
    bid int auto_increment primary key not null COMMENT'图书编号',
    bname varchar(50) not null COMMENT'图书名称',
    bauthor VARCHAR(50) COMMENT'图书作者'
)
INSERT into book(bname,bauthor)VALUES
('斗罗大陆','唐家三少'),
('假如给我三天光明','海伦凯勒'),
('斗破苍穹','天蚕土豆'),
('雪鹰领主','我吃西红柿')
SELECT * from book

后台

后台的话我就提供一些比较重要的部分,因为搭建好这整个项目之后,你就知道那些部分是重要,整体的项目结构如下:

我这里使用的是一个练习的,主要是搭建ssm项目非常的消耗时间,所以就是用以前搭建好的,我会将重要的文件抽取出来,提供给搭建使用

(1)Erp_Common下有一个通用返回消息的类R

R.java

package com.erp.common;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回数据封装
 */
public class R extends HashMap<String, Object> {
    private static final long serialVersionUID = 1L;
    
    public R() {
        put("code", 1);
        put("msg", "success");
    }

    //错误时
    public static R error() {
        return error(500, "未知异常,请联系管理员");
    }
    
    public static R error(String msg) {
        return error(500, msg);
    }
    
    public static R error(int code, String msg) {
        R r = new R();
        r.put("code", code);
        r.put("msg", msg);
        return r;
    }

    //成功时
    public static R ok(String msg) {
        R r = new R();
        r.put("msg", msg);
        return r;
    }
    
    public static R ok(Map<String, Object> map) {
        R r = new R();
        r.putAll(map);
        return r;
    }
    
    public static R ok() {
        return new R();
    }

    public static R ok(Object data) {
        return new R().put("data",data);
    }

    @Override
    public R put(String key, Object value) {
        super.put(key, value);
        return this;
    }
}
View Code

(2)Erp_Dao模块下的BookDao,BookMapper.xml,applicationContext.xml,db.properties,mybatis.xml,ErpDaoTest

BookDao

package com.erp.dao;

import com.erp.entities.Book;

import java.util.List;

public interface BookDao {
    //查询全部图书
    List<Book> getAllBook();
    //添加图书
    boolean addBook(Book book);
    //修改图书
    boolean updateBook(Book book);
    //删除图书
    boolean deleteBook(int bid);
    //更据编号查询图书信息
    Book getBookById(int bid);
}
View Code

BookMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--命名空间应该是对应接口的包名+接口名 -->
<mapper namespace="com.erp.dao.BookDao">
    <!--查询全部图书-->
    <select id="getAllBook" resultMap="bookMap">
        select  bid,bname,bauthor from book
    </select>
    <!--根据编号查询图书信息-->
    <select id="getBookById" resultType="book">
        select bid,bname,bauthor from  book where bid=#{id}
    </select>
    <!--添加图书-->
    <insert id="addBook" parameterType="book">
      insert  into book(bname, bauthor)
      values (#{bname},#{bauthor})
    </insert>
    <!--修改图书信息-->
    <update id="updateBook" parameterType="book">
      update book set bname=#{bname},bauthor=#{bauthor} where bid=#{bid}
    </update>
    <!--删除图书信息-->
    <delete id="deleteBook" parameterType="int">
      delete  from book where  bid=#{bid}
    </delete>
    <resultMap id="bookMap" type="book">
        <id property="bid" column="bid"/>
        <result column="bname" property="bname"/>
        <result property="bauthor" column="bauthor"/>
    </resultMap>
</mapper>
View Code

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <!--1 引入属性文件,在配置中占位使用 -->
    <context:property-placeholder location="classpath*:db.properties" />

    <!--2 配置C3P0数据源 -->
    <bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <!--驱动类名 -->
        <property name="driverClass" value="${mysql.driver}" />
        <!-- url -->
        <property name="jdbcUrl" value="${mysql.url}" />
        <!-- 用户名 -->
        <property name="user" value="${mysql.uid}" />
        <!-- 密码 -->
        <property name="password" value="${mysql.password}" />
        <!-- 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数 -->
        <property name="acquireIncrement" value="${mysql.acquireIncrement}"></property>
        <!-- 初始连接池大小 -->
        <property name="initialPoolSize" value="${mysql.initialPoolSize}"></property>
        <!-- 连接池中连接最小个数 -->
        <property name="minPoolSize" value="${mysql.minPoolSize}"></property>
        <!-- 连接池中连接最大个数 -->
        <property name="maxPoolSize" value="${mysql.maxPoolSize}"></property>
    </bean>

    <!--3 会话工厂bean sqlSessionFactoryBean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- mybatis核心配置文件路径 -->
        <property name="configLocation" value="classpath:mybatis.xml"></property>
        <!-- 数据源 -->
        <property name="dataSource" ref="datasource"/>
        <!-- sql映射文件路径[mapper路径] -->
        <property name="mapperLocations" value="classpath*:mapper/*Mapper.xml"></property>
    </bean>

    <!--4 自动扫描对象关系映射 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定会话工厂,如果当前上下文中只定义了一个则该属性可省去 -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 指定要自动扫描接口的基础包,实现接口 -->
        <property name="basePackage" value="com.erp.dao"/>
    </bean>

    <!--5 声明式事务管理 -->
    <!--定义事物管理器,由spring管理事务 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="datasource"></property>
    </bean>
    <!--支持注解驱动的事务管理,指定事务管理器 -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!--6 容器自动扫描IOC组件 -->
    <context:component-scan base-package="com.erp"/>

    <!--7 aspectj支持自动代理实现AOP功能 -->
    <aop:aspectj-autoproxy/>

</beans>
View Code

db.properties

##mysql连接字符串
#驱动
mysql.driver=com.mysql.jdbc.Driver
#连接字符串
mysql.url=jdbc:mysql://localhost:3306/booksystem?useUnicode=true&amp;characterEncoding=UTF-8
#用户名
mysql.uid=root
#密码
mysql.password=123456
mysql.acquireIncrement=5
mysql.initialPoolSize=10
mysql.minPoolSize=5
mysql.maxPoolSize=20
View Code

mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="db.properties"></properties>
    <settings>
        <!--指定mybatis使用日志组件 -->
         <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!--设置别名-->
    <typeAliases>
        <package name="com.erp.entities"/>
    </typeAliases>
</configuration>
View Code

ErpDaoTest

package com.erp.dao;

import com.erp.entities.Book;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import static org.junit.Assert.*;
//指定bean注入的配置文件
@ContextConfiguration("/applicationContext.xml")
//使用标准的junit
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional    //事务管理
@Rollback(true) //是否回滚
public class ErpDaoTest {
    @Autowired
    private ErpDao erpDao;
    @Autowired
    private  BookDao bookDao;
    @Test
    public void getAll() {
//        System.out.println(bookDao.getAllBook());
        Book book=new Book(1,"你好","aa");
//        bookDao.updateBook(book);
        bookDao.getBookById(1);
    }

}
View Code

(3)Erp_Entity模块下的Book.java

 Book.java

package com.erp.entities;

public class Book {

  private long bid;     //  图书编号
  private String bname; //  图书名称
  private String bauthor; //  图书作者
  public long getBid() {
    return bid;
  }

  public void setBid(long bid) {
    this.bid = bid;
  }


  public String getBname() {
    return bname;
  }

  public void setBname(String bname) {
    this.bname = bname;
  }


  public String getBauthor() {
    return bauthor;
  }

  public void setBauthor(String bauthor) {
    this.bauthor = bauthor;
  }
  //  无参构造方法
  public Book() {
  }
  //带参构造方法
  public Book(long bid, String bname, String bauthor) {
    this.bid = bid;
    this.bname = bname;
    this.bauthor = bauthor;
  }

  @Override
  public String toString() {
    return "Book{" +
            "bid=" + bid +
            ", bname='" + bname + '\'' +
            ", bauthor='" + bauthor + '\'' +
            '}';
  }
}
View Code

(4)Erp_Service模块下的BookService和BookImple

BookService

package com.erp.service;

import com.erp.entities.Book;

import java.util.List;

public interface BookService {
    //  查询全部图书信息
    List<Book> getAllBook();
    //  根据图书编号查询图书信息
    Book getBookById(int id);
    //添加图书
    boolean addBook(Book book);
    //修改图书
    boolean updateBook(Book book);
    //删除图书
    boolean deleteBook(int id);
}
View Code

BookImple

package com.erp.service.imple;

import com.erp.dao.BookDao;
import com.erp.entities.Book;
import com.erp.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class BookImple implements BookService {
    @Autowired
    private BookDao bookDao;
    public List<Book> getAllBook() {
        return bookDao.getAllBook();
    }

    public Book getBookById(int id) {
        return bookDao.getBookById(id);
    }

    public boolean addBook(Book book) {
        return bookDao.addBook(book);
    }

    public boolean updateBook(Book book) {
        return bookDao.updateBook(book);
    }

    public boolean deleteBook(int id) {
        return bookDao.deleteBook(id);
    }
}
View Code

(5)Erp_WebUi模块下的BookController,springmvc-servlet.xml,web.xml

 BookController

package com.erp.controller;

import com.erp.common.R;
import com.erp.entities.Book;
import com.erp.service.BookService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;
    //  查询全部图书信息
    @ResponseBody
    @RequestMapping("/getAllBook")
    public R getAllBook(){
        return  R.ok(bookService.getAllBook());
    }
    //  根据图书编号查询图书信息
    @ResponseBody
    @RequestMapping("/getBookById")
    public  R getBookById(@RequestParam("id") Integer id){
        try {
            return  R.ok(bookService.getBookById(id));
        }catch (Exception e){
            return  R.error("参数错误");
        }
    }
    //  添加图书
    @ResponseBody
    @PostMapping("/addBook")
    public  R addBook(@RequestParam("bname") String bname,@RequestParam("bauthor") String bauthor){
        try {
            Book book=new Book(0,bname,bauthor);
            return  R.ok(bookService.addBook(book));
        }catch (Exception e){
            return  R.error("参数错误");
        }
    }
    @ResponseBody
    @PutMapping("/updateBook")
    //  修改图书
    public  R updateBook(@RequestParam("bid") Integer bid,@RequestParam("bname") String bname,@RequestParam("bauthor") String bauthor){
        try {
            Book book=new Book(bid,bname,bauthor);
            return  R.ok(bookService.updateBook(book));
        }catch (Exception e){
            return  R.error("参数错误");
        }
    }
    //  删除图书
    @ResponseBody
    @DeleteMapping("/deleteBook")
    public  R deleteBook(@RequestParam("id") Integer id){
        try {
            return R.ok(bookService.deleteBook(id));
        }catch (Exception e){
            return  R.error("参数错误");
        }
    }
}
View Code

在这个控制器中我们使用的是Restful的风格来进行响应

springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
    
    <!-- 自动扫描包,实现支持注解的IOC -->
    <context:component-scan base-package="com.erp" />

    <!-- Spring MVC不处理静态资源 -->
    <mvc:default-servlet-handler />

    <!-- 支持mvc注解驱动 -->
    <mvc:annotation-driven enable-matrix-variables="true" />

    <!-- 配置映射媒体类型的策略 -->
    <bean
            class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
        <property name="removeSemicolonContent" value="false" />
    </bean>

    <!-- 内部视图解析器,JSP与JSTL模板 -->
    <bean
            class="org.springframework.web.servlet.view.InternalResourceViewResolver"
            id="internalResourceViewResolver">
        <!--指定视图渲染类 -->
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView" />
        <!--自动添加到路径中的前缀 -->
        <property name="prefix" value="/WEB-INF/views/" />
        <!--自动添加到路径中的后缀 -->
        <property name="suffix" value=".jsp" />
        <!--设置所有视图的内容类型,如果视图本身设置内容类型视图类可以忽略 -->
        <property name="contentType" value="text/html;charset=UTF-8" />
        <!-- 优先级,越小越前 -->
        <property name="order" value="1" />
    </bean>

        <!--文件上传解析器 -->
    <!--Spring MVC默认不能识别multipart格式的文件内容 -->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
    </bean>
    <mvc:cors>
        <mvc:mapping path="/**"
                     allowed-origins="*"
                     allowed-methods="POST,GET, OPTIONS,DELETE,PUT"
                     allowed-headers="Content-Type,ContentType,Access-Control-Allow-Headers, Authorization, X-Requested-With"
                     allow-credentials="true"/>
    </mvc:cors>

</beans>
View Code

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

  <listener>
    <description>Spring容器加载监听器</description>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <description>设置Spring加载时的配置文件位置,默认位置在WEB-INF/lib目录下</description>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext.xml</param-value>
  </context-param>

  <!--Spring MVC 前置Servlet,中心控制器 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <!--Spring MVC配置文件路径 -->
      <param-value>classpath*:springmvc-servlet.xml</param-value>
    </init-param>
    <!-- 启动动优先级,越小越早加载 -->
    <load-on-startup>1</load-on-startup>
    <!--Servlet3.0以上文件上传配置 -->
    <multipart-config>
      <!--上传文件的最大限制5MB -->
      <max-file-size>5242880</max-file-size>
      <!--请求的最大限制20MB -->
      <max-request-size>20971520</max-request-size>
      <!--当文件的大小超过临界值时将写入磁盘 -->
      <file-size-threshold>0</file-size-threshold>
    </multipart-config>
  </servlet>
  <!-- Servlet访问的路径映射,所有的访问都必须经过调度用的前置控制品 -->
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!--编码过滤器 -->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <!-- 路径映射 -->
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
View Code

整体的后台已经搭建完成了,现在就是在前端使用axios来请求数据和处理数据了

axios的请求方式

在编写前端代码之前我们需要了解axios的一些请求方式

1.基本请求方式

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]])

注意当使用别名方法时,不需要在config中指定url,method和data属性。

2.并发请求

axios.all(iterable)
axios.spread(callback)

3.请求配置

{
// `url`是将用于请求的服务器URL
url: '/user',

// `method`是发出请求时使用的请求方法
method: 'get', // 默认

// `baseURL`将被添加到`url`前面,除非`url`是绝对的。
// 可以方便地为 axios 的实例设置`baseURL`,以便将相对 URL 传递给该实例的方法。
baseURL: 'https://some-domain.com/api/',

// `transformRequest`允许在请求数据发送到服务器之前对其进行更改
// 这只适用于请求方法'PUT','POST'和'PATCH'
// 数组中的最后一个函数必须返回一个字符串,一个 ArrayBuffer或一个 Stream

transformRequest: [function (data) {
// 做任何你想要的数据转换

return data;
}],

// `transformResponse`允许在 then / catch之前对响应数据进行更改
transformResponse: [function (data) {
// Do whatever you want to transform the data

return data;
}],

// `headers`是要发送的自定义 headers
headers: {'X-Requested-With': 'XMLHttpRequest'},

// `params`是要与请求一起发送的URL参数
// 必须是纯对象或URLSearchParams对象
params: {
ID: 12345
},

// `paramsSerializer`是一个可选的函数,负责序列化`params`
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},

// `data`是要作为请求主体发送的数据
// 仅适用于请求方法“PUT”,“POST”和“PATCH”
// 当没有设置`transformRequest`时,必须是以下类型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream
data: {
firstName: 'Fred'
},

// `timeout`指定请求超时之前的毫秒数。
// 如果请求的时间超过'timeout',请求将被中止。
timeout: 1000,

// `withCredentials`指示是否跨站点访问控制请求
// should be made using credentials
withCredentials: false, // default

// `adapter'允许自定义处理请求,这使得测试更容易。
// 返回一个promise并提供一个有效的响应(参见[response docs](#response-api))
adapter: function (config) {
/* ... */
},

// `auth'表示应该使用 HTTP 基本认证,并提供凭据。
// 这将设置一个`Authorization'头,覆盖任何现有的`Authorization'自定义头,使用`headers`设置。
auth: {
username: 'janedoe',
password: 's00pers3cret'
},

// “responseType”表示服务器将响应的数据类型
// 包括 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default

//`xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名称
xsrfCookieName: 'XSRF-TOKEN', // default

// `xsrfHeaderName`是携带xsrf令牌值的http头的名称
xsrfHeaderName: 'X-XSRF-TOKEN', // default

// `onUploadProgress`允许处理上传的进度事件
onUploadProgress: function (progressEvent) {
// 使用本地 progress 事件做任何你想要做的
},

// `onDownloadProgress`允许处理下载的进度事件
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},

// `maxContentLength`定义允许的http响应内容的最大大小
maxContentLength: 2000,

// `validateStatus`定义是否解析或拒绝给定的promise
// HTTP响应状态码。如果`validateStatus`返回`true`(或被设置为`null` promise将被解析;否则,promise将被
// 拒绝。
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},

// `maxRedirects`定义在node.js中要遵循的重定向的最大数量。
// 如果设置为0,则不会遵循重定向。
maxRedirects: 5, // 默认

// `httpAgent`和`httpsAgent`用于定义在node.js中分别执行http和https请求时使用的自定义代理。
// 允许配置类似`keepAlive`的选项,
// 默认情况下不启用。
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),

// 'proxy'定义代理服务器的主机名和端口
// `auth`表示HTTP Basic auth应该用于连接到代理,并提供credentials。
// 这将设置一个`Proxy-Authorization` header,覆盖任何使用`headers`设置的现有的`Proxy-Authorization` 自定义 headers。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: : {
username: 'mikeymike',
password: 'rapunz3l'
}
},

// “cancelToken”指定可用于取消请求的取消令牌
// (see Cancellation section below for details)
cancelToken: new CancelToken(function (cancel) {
})
}

4. 响应模式

请求的响应包含以下信息

{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the headers that the server responded with
  // All header names are lower cased
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance in the browser
  request: {}
}

使用时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);
});

5.配置默认值

您可以指定将应用于每个请求的配置默认值

5.1全局axios默认值
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
5.2自定义实例默认值
//在创建实例时设置配置默认值
var instance = axios.create({
  baseURL:'https://api.example.com'
});

//在实例创建后改变默认值
instance.defaults.headers.common ['Authorization'] = AUTH_TOKEN;

6.配置优先级顺序

配置将与优先顺序合并。 顺序是lib / defaults.js中的库默认值,然后是实例的defaults属性,最后是请求的config参数。 后者将优先于前者。 这里有一个例子

//使用库提供的配置默认值创建实例
//此时,超时配置值为`0`,这是库的默认值
var instance = axios.create();

//覆盖库的超时默认值
//现在所有请求将在超时前等待2.5秒
instance.defaults.timeout = 2500;

//覆盖此请求的超时,因为它知道需要很长时间
instance.get('/ longRequest',{
timeout:5000
})

前端

普通界面版

1.处理get请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>axios处理GET请求</title>
</head>
<body>
  <div id="app">
      <button @click="getAllBook">获取全部的图书</button>
  </div>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    const vm=new Vue({
      el:'#app',
      data:{
        baseUrl:"http://localhost:8088/book/"
      },
      methods:{
        getAllBook(){
          //方式一
          // axios.get(this.baseUrl+'getAllBook').then((response)=>{
          //   console.log(response);
          // })
          //方式二
          axios({
            url:this.baseUrl+'getAllBook',
            method:"GET",
          }).then((response)=>{
            console.log(response);
          })
        }
      }
    })
  </script>
</body>
</html>

结果:

2.处理post请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>axios处理POST请求</title>
</head>
<body>
  <div id="app">
      <button @click="addBook">添加书籍</button>
  </div>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    const vm=new Vue({
      el:'#app',
      data:{
        baseUrl:'http://localhost:8088/book/'
      },
      methods:{
        addBook(){
          axios({
            url:this.baseUrl+'addBook',
            method:'POST',
            params:{
                   bname:'vue从入门到进阶',
                   bauthor:'一只流浪的kk'
            }
          }).then((response)=>{
            console.log(response);
          })
        }
      }
    })
  </script>
</body>
</html>

结果:

3.处理put请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>axios处理PUT请求</title>
</head>
<body>
  <div id="app">
      <button @click="updateBook">修改图书信息</button>
  </div>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    const vm=new Vue({
      el:'#app',
      data:{
        baseUrl:'http://localhost:8088/book/'
      },
      methods:{
        updateBook(){
          axios({
            url:this.baseUrl+'updateBook',
            method:'PUT',
            params:{
              bid:5,
              bname:'java从入门到精通',
              bauthor:'中本聪'
            }
          }).then((response)=>{
            console.log(response);
          })
        }
      }
    })
  </script>
</body>
</html>

结果:

4.处理delete请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>axios处理DELETE请求</title>
</head>
<body>
  <div id="app">
    <button @click="deleteBook">删除图书信息</button>
  </div>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    const vm=new Vue({
      el:'#app',
      data:{
        baseUrl:'http://localhost:8088/book/'
      },
      methods:{
        deleteBook(){
          axios({
            url:this.baseUrl+'deleteBook',
            method:'DELETE',
            params:{
              id:5
            }
          }).then((response)=>{
            console.log(response);
          })
        }
      }
    })
  </script>
</body>
</html>

结果:

5.处理多个请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>axios处理多个请求</title>
</head>
<body>
  <div id="app">
    <button @click="getBookById">查询多本图书信息</button>
  </div>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    const vm=new Vue({
      el:'#app',
      data:{
        baseUrl:'http://localhost:8088/book/'
      },
      methods:{
        getBookById(){
          const that=this;
          const getBookOne=function () {
            return axios({
              url:that.baseUrl+'getBookById',
              method:'GET',
              params:{
                id:1
              }
            });
          }
          const getBookTwo=function () {
            return axios({
                url:that.baseUrl+'getBookById',
                method:'GET',
                params:{
                  id:2
                }
            })
          }
          axios.all([getBookOne(),getBookTwo()]).then(axios.spread(function (data1,data2) {
            console.log(data1);
            console.log(data2);
          }))
        }
      }
    })
  </script>
</body>
</html>

结果:

posted @ 2019-12-23 10:13  二郎神杨戬  阅读(11170)  评论(0编辑  收藏  举报