一文搞懂前后端通讯—Axios神器

一文搞懂前后端通讯—Axios神器

一、后端接口SpringBoot+Mysql搭建

项目目录

image-20210706134724363

maven依赖pom.xml
 
 

xml

复制代码

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.sxau</groupId> <artifactId>sringbootjwt</artifactId> <version>0.0.1-SNAPSHOT</version> <name>sringbootjwt</name> <description>token</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- mysql-connector--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> <!-- lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!-- p6spy 打印sql分析依赖--> <dependency> <groupId>p6spy</groupId> <artifactId>p6spy</artifactId> <version>3.9.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.75</version> </dependency> <!-- 代码生成器--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

application.yaml
 
 

yaml

复制代码

server: port: 10086 #数据库配置 spring: datasource: username: root password: 123456 #p6spy 驱动url url: jdbc:p6spy:mysql://localhost:3306/mybatis_plus?userSSL=false&useUnicode=true&CharacterEncoding=utf-8&serverTimezone=GMT%2B8 # p6spy 驱动 driver-class-name: com.p6spy.engine.spy.P6SpyDriver # profiles: # active: dev #mybatis-plus日志配置文件 mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl global-config: db-config: logic-delete-field: flag # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2) logic-delete-value: 1 # 逻辑已删除值(默认为 1) logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

spy.properties
 
 

properties

复制代码

#3.2.1以上使用 modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory # 自定义日志打印 logMessageFormat=com.sxau.sringbootjwt.utils.P6SpySqlLog #日志输出到控制台 appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger # 使用日志系统记录 sql #appender=com.p6spy.engine.spy.appender.Slf4JLogger # 设置 p6spy driver 代理 deregisterdrivers=true # 取消JDBC URL前缀 useprefix=true # 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset. excludecategories=info,debug,result,commit,resultset # 日期格式 dateformat=yyyy-MM-dd HH:mm:ss # 实际驱动可多个 #driverlist=org.h2.Driver # 是否开启慢SQL记录 outagedetection=true # 慢SQL记录标准 2 秒 outagedetectioninterval=2

利用代码生成器生成对应的文件
 
 

java

复制代码

package com.sxau.sringbootjwt; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; import com.baomidou.mybatisplus.generator.config.GlobalConfig; import com.baomidou.mybatisplus.generator.config.PackageConfig; import com.baomidou.mybatisplus.generator.config.StrategyConfig; import com.baomidou.mybatisplus.generator.config.po.TableFill; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import java.util.ArrayList; // 代码自动生成器 public class test { public static void main(String[] args) { // 需要构建一个 代码自动生成器 对象 AutoGenerator mpg = new AutoGenerator(); // 配置策略 // 1、全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath+"/src/main/java/SpringBoot主启动项目名"); gc.setAuthor("张晟睿"); gc.setOpen(false); gc.setFileOverride(false); // 是否覆盖 gc.setServiceName("%sService"); // 去Service的I前缀 gc.setIdType(IdType.ID_WORKER); mpg.setGlobalConfig(gc); //2、设置数据源 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc); //3、包的配置 PackageConfig pc = new PackageConfig(); //只需要改实体类名字 和包名 还有 数据库配置即可 pc.setModuleName(""); pc.setParent("com.sxau"); pc.setEntity("entity"); pc.setMapper("mapper"); pc.setService("service"); pc.setController("controller"); mpg.setPackageInfo(pc); //4、策略配置 StrategyConfig strategy = new StrategyConfig(); //在此处添加包名 strategy.setInclude("user"); // 设置要映射的表名 strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); // 自动lombok; strategy.setLogicDeleteFieldName("deleted"); // 自动填充配置 TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT); TableFill gmtModified = new TableFill("gmt_modified",FieldFill.INSERT_UPDATE); ArrayList<TableFill> tableFills = new ArrayList<>(); tableFills.add(gmtCreate); tableFills.add(gmtModified); strategy.setTableFillList(tableFills); // 乐观锁 strategy.setVersionFieldName("version"); strategy.setRestControllerStyle(true); strategy.setControllerMappingHyphenStyle(true); // localhost:8080/hello_id_2 mpg.setStrategy(strategy); mpg.execute(); //执行 } }

UserController.java
 
 

java

复制代码

package com.sxau.sringbootjwt.controller; import com.alibaba.fastjson.JSON; import com.sxau.sringbootjwt.mapper.UserMapper; import com.sxau.sringbootjwt.pojo.User; import com.sxau.sringbootjwt.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.List; import java.util.Map; /** * <p> * 前端控制器 * </p> * * @author 张晟睿 * @since 2021-07-05 */ @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @CrossOrigin @RequestMapping("/getAllUser") public String getAllUser(){ Map<String,Object> resultData=new HashMap<String, Object>(); List<User> users = userService.selectAllUser(); resultData.put("ret","1"); resultData.put("data",users); resultData.put("msg","成功"); return JSON.toJSONString(resultData); } @CrossOrigin @RequestMapping("/findUserById") public String findUserById(Integer id){ Map<String,Object> resultData=new HashMap<String, Object>(); User userById = userService.findUserById(id); resultData.put("ret","1"); resultData.put("data",userById); resultData.put("msg","成功"); return JSON.toJSONString(resultData); } @RequestMapping("/findUserByAge") public String findUserByAge(Integer age){ Map<String,Object> resultData=new HashMap<String, Object>(); List<Map<String, Object>> userListAge = userService.findUserListAge(age); resultData.put("ret","1"); resultData.put("data",userListAge); resultData.put("msg","成功"); return JSON.toJSONString(resultData); } @RequestMapping("/hello") public String hello(){ return "hello,springboot"; } }

UserMapper.java
 
 

java

复制代码

package com.sxau.sringbootjwt.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.sxau.sringbootjwt.pojo.User; public interface UserMapper extends BaseMapper<User> { }

User.java
 
 

java

复制代码

package com.sxau.sringbootjwt.pojo; import com.baomidou.mybatisplus.annotation.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; @Data @NoArgsConstructor @AllArgsConstructor public class User { //主键自增配合 数据库主键自增使用 @TableId(type = IdType.AUTO) private Long id; private String name; private int age; private String email; @TableLogic private Integer deleted; //逻辑删除 @TableField(fill = FieldFill.INSERT) private Date createTime; //开始时间 @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime; //更新时间 }

UserService.java
 
 

java

复制代码

package com.sxau.sringbootjwt.service; import com.sxau.sringbootjwt.pojo.User; import java.util.List; import java.util.Map; /** * <p> * 服务类 * </p> * * @author 张晟睿 * @since 2021-07-05 */ public interface UserService { List<User> selectAllUser(); User findUserById(Integer id); List<Map<String, Object>> findUserListAge(Integer age); }

UserServiceImpl.java
 
 

java

复制代码

package com.sxau.sringbootjwt.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.sxau.sringbootjwt.mapper.UserMapper; import com.sxau.sringbootjwt.pojo.User; import com.sxau.sringbootjwt.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; /** * <p> * 服务实现类 * </p> * * @author 张晟睿 * @since 2021-07-05 */ @Service public class UserServiceImpl implements UserService { @Autowired UserMapper userMapper; @Override public List<User> selectAllUser() { List<User> users = userMapper.selectList(null); return users; } @Override public User findUserById(Integer id) { User user = userMapper.selectById(id); return user; } @Override public List<Map<String, Object>> findUserListAge(Integer age) { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.gt("age",age); List<Map<String, Object>> maps = userMapper.selectMaps(wrapper); return maps; } }

输出格式化P6SpySqlLog.java
 
 

java

复制代码

package com.sxau.sringbootjwt.utils; import com.p6spy.engine.spy.appender.MessageFormattingStrategy; import java.text.SimpleDateFormat; import java.util.Date; public class P6SpySqlLog implements MessageFormattingStrategy { private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); @Override public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String s4) { return !"".equals(sql.trim()) ? this.format.format(new Date()) + " | cost " + elapsed + " ms | " + category + " | connection " + connectionId + "\n " + sql + ";" : ""; } }

SpringBoot主启动类
 
 

java

复制代码

package com.sxau.sringbootjwt; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @MapperScan("com.sxau.sringbootjwt.mapper") //@ComponentScan("com.sxau.sringbootjwt.handle") @SpringBootApplication(scanBasePackages = "com") public class SringbootjwtApplication { public static void main(String[] args) { SpringApplication.run(SringbootjwtApplication.class, args); } }

数据库表设计

image-20210706135316899

插入数据

 
 

sql

复制代码

INSERT INTO `user` (`id`, `name`, `age`, `email`, `deleted`, `create_time`, `update_time`) VALUES (1, 'Jone', 18, '[email protected]', 0, NULL, NULL); INSERT INTO `user` (`id`, `name`, `age`, `email`, `deleted`, `create_time`, `update_time`) VALUES (2, 'Jack', 20, '[email protected]', 0, NULL, NULL); INSERT INTO `user` (`id`, `name`, `age`, `email`, `deleted`, `create_time`, `update_time`) VALUES (3, 'Tom', 28, '[email protected]', 0, NULL, NULL); INSERT INTO `user` (`id`, `name`, `age`, `email`, `deleted`, `create_time`, `update_time`) VALUES (4, 'Sandy', 21, '[email protected]', 0, NULL, NULL); INSERT INTO `user` (`id`, `name`, `age`, `email`, `deleted`, `create_time`, `update_time`) VALUES (5, 'Billie', 24, '[email protected]', 0, NULL, NULL); INSERT INTO `user` (`id`, `name`, `age`, `email`, `deleted`, `create_time`, `update_time`) VALUES (201916129, '张三', 20, '[email protected]', 1, NULL, '2021-07-03 16:15:38'); INSERT INTO `user` (`id`, `name`, `age`, `email`, `deleted`, `create_time`, `update_time`) VALUES (201916137, '李丽1', 20, '[email protected]', 0, '2021-07-03 18:21:56', '2021-07-04 11:49:51'); INSERT INTO `user` (`id`, `name`, `age`, `email`, `deleted`, `create_time`, `update_time`) VALUES (201916141, '渣渣辉1', 50, '[email protected]', 0, '2021-07-04 14:49:04', '2021-07-04 14:49:04'); INSERT INTO `user` (`id`, `name`, `age`, `email`, `deleted`, `create_time`, `update_time`) VALUES (201916142, '渣渣辉2', 10, '[email protected]', 0, '2021-07-04 14:49:48', '2021-07-04 14:49:48');

测试后端接口

image-20210706135527394

image-20210706135624927

image-20210706135737486

二、axios基本使用

 
 

js

复制代码

<script src="https://unpkg.com/axios/dist/axios.min.js"></script> <!--使用默认方式发送无参请求--> <script> axios({ url: 'http://localhost:10086/user/getAllUser' }).then(res=>{ console.log(res); }) </script>

axios发送get请求

 
 

js

复制代码

<script src="https://unpkg.com/axios/dist/axios.min.js"></script> <!--使用get方式发送无参请求--> <script> axios({ url: 'http://localhost:10086/user/getAllUser', method: 'get' }).then(res=>{ console.log(res); }) </script> 第一种:使用get方式发送有参请求 <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <!--使用get方式发送有参请求--> <script> axios({ url: 'http://localhost:10086/user/findUserById?id=1', method: 'get' }).then(res=>{ console.log(res); }) </script> 第二种:使用get方式发送有参请求 <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <!--使用get方式发送有参请求--> <script> axios({ url: 'http://localhost:10086/user/findUserById', method: 'get', params:{ id: '1' } }).then(res=>{ console.log(res); }) </script>

axios发送post请求

 
 

xml

复制代码

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

 
 

js

复制代码

<script src="https://unpkg.com/axios/dist/axios.min.js"></script> <!--使用post方式发送无参请求--> <script> axios({ url: 'http://localhost:10086/user/getAllUser', method: 'post' }).then(res=>{ console.log(res); }) </script>

 
 

js

复制代码

<script src="https://unpkg.com/axios/dist/axios.min.js"></script> <!--使用post方式发送有参请求--> <script> axios({ url: 'http://localhost:10086/user/findUserByAge', data:{ age:'20' }, method: 'post' }).then(res=>{ console.log(res); }) </script>

后台控制器接收到的name null axios使 用post携带参数请求默认使用application/ json 解决方式- : params属性进行数据的传递 解决方式二: "name=张三” 解决方式三:服务器端给接收的参 数加上@reques tBody

三、axios简写使用

 
 

js

复制代码

<!--使用get方式发送单个参请求--> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script> axios.get('http://localhost:10086/user/findUserById',{params:{id:1}}).then(res=>{ console.log(res); }).catch(err=>{ console.log("timeout"); console.log(err); }) </script>

 
 

js

复制代码

<!--使用get方式发送多个参数请求--> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script> axios.get('http://localhost:10086/user/findUserById',{params:{id:1,name:zhangsan}}).then(res=>{ console.log(res); }).catch(err=>{ console.log("timeout"); console.log(err); }) </script>

推荐使用

 
 

js

复制代码

<script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script> axios.post('http://localhost:10086/user/findUserById','id=1').then(res=>{ console.log(res); }).catch(err=>{ console.log("timeout"); console.log(err); }) </script> //发送post请求携带参数 直接使用'id=1&name=jack'

 
 

js

复制代码

//这种情况下通过data传值 值能传递过去 但是拿到的值为not found //使用data传递数据后台需要将axi so自动装换的json数据装换为java对象//修改后台代码 接受参数用@requestBody注解 <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script> axios.post('http://localhost:10086/user/findUserById',{id: 1}).then(res=>{ console.log(res); }).catch(err=>{ console.log("timeout"); console.log(err); }) </script>

四、axios并发

第一种方式
 
 

js

复制代码

//通过并发拿到all里面的两个get请求的数组 <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script> axios.all([ axios.get('http://localhost:10086/user/getAllUser'), axios.get('http://localhost:10086/user/findUserByAge',{params:{age:20}}) ]).then(res=>{ console.log(res); }).catch(err=>{ console.log("timeout"); console.log(err); }) </script>

image-20210706173737127

第二种方式
 
 

js

复制代码

<script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script> axios.all([ axios.get('http://localhost:10086/user/getAllUser'), axios.get('http://localhost:10086/user/findUserByAge',{params:{age:20}}) ]).then( axios.spread((res1,res2)=>{ console.log(res1); console.log(res2); }) ).catch(err=>{ console.log("timeout"); console.log(err); }) </script>

image-20210706174103260

五、全局配置

 
 

js

复制代码

<script> axios.defaults.baseURL='htttp://localhost:10086/user'; axios.defaults.timeout=5000; axios.get('getAllUser').then(res=>{ console.log(res); }); axios.post('findUserById','id=1').then(res=>{ console.log(res); }).catch(err=>{ console.log(err); }) </script>

六、拦截器

 
 

js

复制代码

//request请求拦截 <script> axios.interceptors.request.use(config=>{ console.log("进入请求拦截器"); console.log(config); return config; },err=>{ console.log("拦截失败"); console.log(err); }); axios.get('http://localhost:10086/user/getAllUser').then(res=>{ console.log(res); }) </script>

 
 

js

复制代码

//response请求拦截 <script> axios.interceptors.response.use(config=>{ console.log("进入请求拦截器"); console.log(config); return config; },err=>{ console.log("拦截失败"); console.log(err); }); axios.get('http://localhost:10086/user/getAllUser').then(res=>{ console.log(res); }) </script>

image-20210708154301501

猜你喜欢

转载自blog.csdn.net/BASK2312/article/details/131811591