vue-cli项目中使用axios
发布日期:2021-05-09 04:02:18 浏览次数:18 分类:博客文章

本文共 16539 字,大约阅读时间需要 55 分钟。

前言

前后端数据交互中,我们使用最多的就是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依赖方法

axios资源:

项目搭建

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

数据库

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
{ 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
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
getAllBook(); //添加图书 boolean addBook(Book book); //修改图书 boolean updateBook(Book book); //删除图书 boolean deleteBook(int bid); //更据编号查询图书信息 Book getBookById(int bid);}
View Code

BookMapper.xml

insert into book(bname, bauthor) values (#{bname},#{bauthor})
update book set bname=#{bname},bauthor=#{bauthor} where bid=#{bid}
delete from book where bid=#{bid}
View Code

applicationContext.xml

View Code

db.properties

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

mybatis.xml

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
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;@Servicepublic class BookImple implements BookService {    @Autowired    private BookDao bookDao;    public List
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

View Code

web.xml

index.html
Spring容器加载监听器
org.springframework.web.context.ContextLoaderListener
设置Spring加载时的配置文件位置,默认位置在WEB-INF/lib目录下
contextConfigLocation
classpath*:applicationContext.xml
springmvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath*:springmvc-servlet.xml
1
5242880
20971520
0
springmvc
/
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
characterEncodingFilter
/*
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`是将用于请求的服务器URLurl: '/user',// `method`是发出请求时使用的请求方法method: 'get', // 默认// `baseURL`将被添加到`url`前面,除非`url`是绝对的。// 可以方便地为 axios 的实例设置`baseURL`,以便将相对 URL 传递给该实例的方法。baseURL: 'https://some-domain.com/api/',// `transformRequest`允许在请求数据发送到服务器之前对其进行更改// 这只适用于请求方法'PUT','POST'和'PATCH'// 数组中的最后一个函数必须返回一个字符串,一个 ArrayBuffer或一个 StreamtransformRequest: [function (data) {// 做任何你想要的数据转换return data;}],// `transformResponse`允许在 then / catch之前对响应数据进行更改transformResponse: [function (data) {// Do whatever you want to transform the datareturn data;}],// `headers`是要发送的自定义 headersheaders: {'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: Streamdata: {firstName: 'Fred'},// `timeout`指定请求超时之前的毫秒数。// 如果请求的时间超过'timeout',请求将被中止。timeout: 1000,// `withCredentials`指示是否跨站点访问控制请求// should be made using credentialswithCredentials: 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请求

    
axios处理GET请求

结果:

2.处理post请求

    
axios处理POST请求

结果:

3.处理put请求

    
axios处理PUT请求

结果:

4.处理delete请求

    
axios处理DELETE请求

结果:

5.处理多个请求

    
axios处理多个请求

结果:

上一篇:vue学习笔记(二)vue的生命周期和钩子函数
下一篇:vue-cli项目中引入第三方插件

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2025年04月20日 01时12分42秒