react使用axios发送请求到后端有很多种方式,但主要还是get和post请求,本文列举实现几种由react发送前端请求,后端使用springboot接受的几种方式
准备工作
1.react需要安装并导入axios
2.建立springboot项目,并在pom文件导入访问web必要的依赖
3.关于跨域问题,出现CORS跨域问题,建议使用springboot配置全局异常类
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("
@Controller
@CrossOrigin
@RequestMapping("/demo1")
public class GetController {
@RequestMapping(value = "/demo1", method = RequestMethod.GET)
@ResponseBody
public String getRequest() {
System.out.println("访问成功");
return "访问成功";
}
}
2.带参的get请求
前端react代码
const id = 1;
axios.get('http://localhost:8081/demo1/demo1/'+id)
.then((response) => {
if (response.status === 200) {
this.setState({
message: response.data
})
}
})
.catch(err => console.log(err))
}
后端springboot代码
@GetMapping(value = "/demo1/{id}")
@ResponseBody
public String get(@PathVariable Integer id) {
System.out.println("访问成功"+id);
return "访问成功";
}
也可以
前端react代码
axios.get('http://localhost:8081/demo1/demo1?params=1')
.then((response) => {
if (response.status === 200) {
this.setState({
message: response.data
})
}
})
.catch(err => console.log(err))
}
后端springboot代码
@GetMapping(value = "/demo1")
@ResponseBody
public String findUserById(HttpServletRequest request) {
Long id = Long.parseLong(request.getParameter("params"));
System.out.println("访问成功"+id);
//返回查找结果
return "查询成功";
}
3.发送post请求
POST请求主要用于携带参数数据较多的情况
前端react代码
const data = {
s : "para1",
data : "2022/5/29"
}
axios.post('http://localhost:8081/demo1/demo1',data)
.then((response) => {
if (response.status === 200) {
this.setState({
message: response.data
})
}
})
.catch(err => console.log(err))
}
后端
@Controller
@CrossOrigin
@RequestMapping("/demo1")
public class PostController {
@RequestMapping(value = "/demo1", method = RequestMethod.POST)
@ResponseBody
public String getRequest(@RequestBody Map data){
System.out.println("访问成功");
System.out.println(data);
return data.get("s").toString() + data.get("date");
}
}
4.携带多个数据参数的axios请求
axios也可以通过下面的方法发送请求,可以将token放在headers中实现对jwt验证
axios({
url: 'url',
method: 'post',
data: 'body',
headers: 'header'})
.then((response) => {
if (response.status === 200) {
this.setState({
message: response.data
})
}
})
.catch(err => console.log(err))
5.封装请求工具类
习惯上,我们会把请求的方式封装成工具类,使用起来就会方便很多,只需要传递相应的参数即可
import { message } from "antd";
import axios from "axios";
class myAxios {
baseUrl = "http://localhost:8081/";
constructor() {
axios.defaults.withCredentials = true
this.myAxios = axios
}
judge(data,resolve ){
if((data.code===1002) || (data.code===2003) ){
message.error(data.message)
}
//成功请求交给各个组件处理
else {
resolve(data)
}
}
post(url, body, params) {
return new Promise((resolve, reject) => {
this.myAxios({
url: this.baseUrl + url,
method: 'post',
data: body
})
.then((res) => {
if (res.status === 200) {
const data = res.data
this.judge(data,resolve)
} else {
reject(new Error("状态值不是200"))
}
})
.catch()
})
}
get(url, params) {
if(params===undefined){
params='';
}
return new Promise((resolve, reject) => {
this.myAxios({
url:this.baseUrl + url,
method:'get',
params:
params
})
.then((res) => {
if (res.status === 200) {
const data = res.data
this.judge(data,resolve)
} else {
reject(new Error("状态值不是200"))
}
})
.catch()
})
}
//下载文件请求
download(url,data,fileType){
let token = window.localStorage.getItem("adminToken");
const res = axios
.request({
url: this.baseUrl+url,
method: "post",
data: data, // 筛选列表的请求参数
responseType: "blob",
})
.then((res) => {
const data = res.data;
let url = window.URL.createObjectURL(data); // 将二进制文件转化为可访问的url
var a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download =fileType ;
a.click(); // 模拟点击下载
window.URL.revokeObjectURL(url);
});
}
//delete请求
delete(url,param) {
return new Promise((resolve,reject)=>{
this.myAxios({
url:this.baseUrl + url,
method:'delete',
params:
param,
})
.then(res=>{
if(res.status===200){
const data=res.data;
this.judge(data,resolve)
}
else{
reject(new Error("状态码不是200"))
}
})
.catch(res=>{
console.log(res);
})
})
}
}
export default new myAxios();
使用工具类发送请求
const onFinish = (values) => {
const user={
username:values.username,
password:values.password,
name:values.name,
sex:values.sex
}
myAxios.post("test/addUser",user)
.then(data=>{
if(data.code===2001){
message.success (data.message)
}
})
};
后端springboot
//添加用户
@PostMapping(value = "/addUser")
@ResponseBody
public ResVO addUser(@RequestBody User user) {
//判断请求用户是否为空
if(user == null){
//用户名为空,返回失败信息
return new ResVO<>(2003, "数据异常", null);
}
//查找相同用户名
Boolean result=userService.addUser(user);
//存在相同用户名,返回相同信息
if(result){
return new ResVO<>(2001, "添加成功", null);
}
return new ResVO<>(2002, "用户名已存在", null);
}
6.源码地址
这里也是通过react和springboot实现了一个管理系统,可以供大家参考
后台管理系统



