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

2023年 7月 19日 112.5k 0

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

一、后端接口SpringBoot+Mysql搭建

项目目录

image-20210706134724363

maven依赖pom.xml


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.5.2
         
    
    com.sxau
    sringbootjwt
    0.0.1-SNAPSHOT
    sringbootjwt
    token
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
        
            mysql
            mysql-connector-java
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.4.0
        
        
        
            org.projectlombok
            lombok
        

        
        
            p6spy
            p6spy
            3.9.0
        

        
        
            com.alibaba
            fastjson
            1.2.75
        
        
        
        
            com.baomidou
            mybatis-plus-generator
            3.4.1
        
        
            org.apache.velocity
            velocity-engine-core
            2.2
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


application.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
#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
利用代码生成器生成对应的文件
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 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
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;

/**
 * 

* 前端控制器 *

* * @author 张晟睿 * @since 2021-07-05 */ @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @CrossOrigin @RequestMapping("/getAllUser") public String getAllUser(){ Map resultData=new HashMap(); List 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 resultData=new HashMap(); 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 resultData=new HashMap(); List 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
package com.sxau.sringbootjwt.mapper;


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sxau.sringbootjwt.pojo.User;

public interface UserMapper extends BaseMapper {
}
User.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
package com.sxau.sringbootjwt.service;


import com.sxau.sringbootjwt.pojo.User;

import java.util.List;
import java.util.Map;

/**
 * 

* 服务类 *

* * @author 张晟睿 * @since 2021-07-05 */ public interface UserService { List selectAllUser(); User findUserById(Integer id); List findUserListAge(Integer age); }
UserServiceImpl.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;

/**
 * 

* 服务实现类 *

* * @author 张晟睿 * @since 2021-07-05 */ @Service public class UserServiceImpl implements UserService { @Autowired UserMapper userMapper; @Override public List selectAllUser() { List users = userMapper.selectList(null); return users; } @Override public User findUserById(Integer id) { User user = userMapper.selectById(id); return user; } @Override public List findUserListAge(Integer age) { QueryWrapper wrapper = new QueryWrapper(); wrapper.gt("age",age); List maps = userMapper.selectMaps(wrapper); return maps; } }
输出格式化P6SpySqlLog.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主启动类
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

插入数据

    INSERT INTO `user` (`id`, `name`, `age`, `email`, `deleted`, `create_time`, `update_time`) VALUES (1, 'Jone', 18, 'test1@baomidou.com', 0, NULL, NULL);
        INSERT INTO `user` (`id`, `name`, `age`, `email`, `deleted`, `create_time`, `update_time`) VALUES (2, 'Jack', 20, 'test2@baomidou.com', 0, NULL, NULL);
        INSERT INTO `user` (`id`, `name`, `age`, `email`, `deleted`, `create_time`, `update_time`) VALUES (3, 'Tom', 28, 'test3@baomidou.com', 0, NULL, NULL);
        INSERT INTO `user` (`id`, `name`, `age`, `email`, `deleted`, `create_time`, `update_time`) VALUES (4, 'Sandy', 21, 'test4@baomidou.com', 0, NULL, NULL);
        INSERT INTO `user` (`id`, `name`, `age`, `email`, `deleted`, `create_time`, `update_time`) VALUES (5, 'Billie', 24, 'test5@baomidou.com', 0, NULL, NULL);
        INSERT INTO `user` (`id`, `name`, `age`, `email`, `deleted`, `create_time`, `update_time`) VALUES (201916129, '张三', 20, '1016942589@qq.com', 1, NULL, '2021-07-03 16:15:38');
        INSERT INTO `user` (`id`, `name`, `age`, `email`, `deleted`, `create_time`, `update_time`) VALUES (201916137, '李丽1', 20, '1016942589@qq.com', 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, '1016942589@qq.com', 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, '1016942589@qq.com', 0, '2021-07-04 14:49:48', '2021-07-04 14:49:48');

测试后端接口

image-20210706135527394

image-20210706135624927

image-20210706135737486

二、axios基本使用

	
	
	
		axios({
			url: 'http://localhost:10086/user/getAllUser'
		}).then(res=>{
			console.log(res);
		})
	

axios发送get请求




	axios({
		url: 'http://localhost:10086/user/getAllUser',
		method: 'get'
	}).then(res=>{
		console.log(res);
	})

第一种:使用get方式发送有参请求

		
		
			axios({
				url: 'http://localhost:10086/user/findUserById?id=1',
				method: 'get'
			}).then(res=>{
				console.log(res);
			})


第二种:使用get方式发送有参请求

		
		
			axios({
				url: 'http://localhost:10086/user/findUserById',
				method: 'get',
				params:{
					id: '1'
				}
			}).then(res=>{
				console.log(res);
			})
		

axios发送post请求

		
	

	
		axios({
			url: 'http://localhost:10086/user/getAllUser',
			method: 'post'
		}).then(res=>{
			console.log(res);
		})

	

	
		axios({
			url: 'http://localhost:10086/user/findUserByAge',
			data:{
				age:'20'
			},
			method: 'post'	
		}).then(res=>{
			console.log(res);
		})

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

三、axios简写使用



		
			axios.get('http://localhost:10086/user/findUserById',{params:{id:1}}).then(res=>{
				console.log(res);
			}).catch(err=>{
				console.log("timeout");
				console.log(err);
			})



		
			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);
			})

推荐使用



		axios.post('http://localhost:10086/user/findUserById','id=1').then(res=>{
			console.log(res);
		}).catch(err=>{
			console.log("timeout");
			console.log(err);
		})

//发送post请求携带参数	直接使用'id=1&name=jack'
//这种情况下通过data传值  值能传递过去 但是拿到的值为not found
//使用data传递数据后台需要将axi so自动装换的json数据装换为java对象//修改后台代码
接受参数用@requestBody注解

		
			axios.post('http://localhost:10086/user/findUserById',{id: 1}).then(res=>{
				console.log(res);
			}).catch(err=>{
				console.log("timeout");
				console.log(err);
			})


四、axios并发

第一种方式
//通过并发拿到all里面的两个get请求的数组

		
			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);
			})

image-20210706173737127

第二种方式

		
			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);
			})
		

image-20210706174103260

五、全局配置


		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);
		})
	

六、拦截器

//request请求拦截

    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);
    })

//response请求拦截

    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);
    })

image-20210708154301501

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论