vue-cli項目中使用axios

前言

先後端數據交互中,咱們使用最多的就是jQuey中的ajax進行數據交互,可是隨着大前端日益的擴大,愈來愈多的庫和框架也漸漸的出如今前端開發人員面前,而本編博客須要介紹的就是在vue-cli項目中使用另外一個庫代替jQuey中的ajax,那就是axios,Vue更新到2.0以後宣告再也不對vue-resource更新,推薦使用axios,axios是一個用於客戶端與服務器通訊的組件,axios 是一個基於Promise 用於瀏覽器和 nodejs 的 HTTP 客戶端javaScript工具。通俗來講能夠實現客戶端請求服務器端提供的服務得到數據。html

本章目標

  • 學會使用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),這篇博客寫的真是很是詳細,博主良心推薦,包教包會,全網最好,沒有之一。那麼開始搭建項目吧!vue

數據庫

sql腳本java

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

後臺

後臺的話我就提供一些比較重要的部分,由於搭建好這整個項目以後,你就知道那些部分是重要,總體的項目結構以下:node

我這裏使用的是一個練習的,主要是搭建ssm項目很是的消耗時間,因此就是用之前搭建好的,我會將重要的文件抽取出來,提供給搭建使用mysql

(1)Erp_Common下有一個通用返回消息的類R

R.javajquery

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

BookDaoios

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.xmlgit

<?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.xmlgithub

<?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>

結果:

相關文章
相關標籤/搜索