(vite+springboot)前后端分离请求到底怎么写,干货来袭

1,800 阅读3分钟

1. Axios 是什么?

Axios是发送ajax请求的,在学习原生js的时候我们会用原生的XMLHttpRequests来发送,但在学习框架当中还使用xhr似乎有些不太方便,axios可立马上手,无需再判断是readyStatue==4了,而且还可以做拦截器。在请求之前与请求之后拦截

在前后端分离的项目中也基本采用这种方式。学习axios的话建议直接看官网,多练习。

Axios 中文文档 | Axios 中文网 | Axios 是一个基于 promise 的网络请求库,可以用于浏览器和 node.js

在此之前

  1. 您需要安装axios
  2. 解决跨域问题
  3. 懂一点springboot

2.跨域问题

跨域违背了同源策略 协议名http 主机名localhost 端口号不同都是跨域了,虽然服务器返回了但是页面收不到数据,下面提供一些解决方案

  1. cors 服务器后端里面有特殊的请求头
  2. jsonp srcript src 不受同源策略 很好用 前后端都要努力,一般不用这种方式 面试喜欢问
  3. 配置代理服务器 类似房屋中介服务器跟服务器之间不受同源策略

接下来讲两种方式大家二选一即可

1. 后端解决跨域(更安全)

注:此时前端不需要配置代理

@Configuration
public class WebMvcConfg implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //设置允许跨域的路径
        registry.addMapping("/**")
                //设置允许跨域请求的域名
                //当**Credentials为true时,**Origin不能为星号,需为具体的ip地址
                .allowedOrigins("http://localhost:3000", "http://127.0.0.1:8082")
                //是否允许证书 不再默认开启
                .allowCredentials(true)
                //设置允许的方法
                .allowedMethods("*")
                //跨域允许时间
                .maxAge(3600);
    }
}

2. 前端配置代理服务器

// vite.config.js
server: {
    // https: true,
    port:3000,
    proxy: {
      '/api': { // 配置需要代理的路径 --> 这里的意思是代理http://localhost:80/api/后的所有路由
        target: 'http://127.0.0.1:8080/', // 目标地址 --> 服务器地址
        changeOrigin: true, // 允许跨域
        ws: true,  // 允许websocket代理
        // 重写路径 --> 作用与vue配置pathRewrite作用相同
        rewrite: (path) => path.replace(/^/api/, "")
      }
    },
  },

如果配置了代理就需要把基准地址设为/apir,如下

需要对axios进行封装,配置一个基准路径,注意不能直接使用axios.post(...),需要先进行封装再暴露出去

// Request.js
import axios from "axios";
const service = axios.create({
    baseURL:'/api', //接口访问的地址
    timeout: 10000,//超时
    headers: {
        'content-type': 'application/json', //axios默认就是json格式
        'X-Requested-With': 'XMLHttpRequest',
    }
});

export default service;

发送请求

import request from '../../Request';
  request.post('register2', {
      phone: ruleForm.phone,
      checkCode: ruleForm.checkCode,
  }).then((data) => {
      console.log(data);
  })

简单的解释一下 <http://localhost:3000/api/register2> 前端配置了基准地址/api,也就是/api/register2,由于配置了代理服务器,在本地路径找不到,就会去请求后端服务器,在请求的时候看到/api就会把地址转给8080这个服务器,并且真实的路径把/api重写为了空字符

3.springboot数据接收

后端如何接收?这里给出两种解决方案

前端发送get请求(params)

axios.get('http://localhost:8080/register3', {
  params:{
    phone: ruleForm.phone,
    checkCode: ruleForm.checkCode,
  }
}).then((data) => {
  console.log(data);
})

后端可以直接映射params参数或者使用@requestParam 这个注解有两个重要属性default 与required 默认数值也就是没有传参数的默认值 required为true必须传入否则为400参数错误@RequestParam(required = false)

//    get请求直接用参数取出 函数的参数必须params的参数名字相同
    @GetMapping(value = "/getTest")
    public String getTest(String phone,String checkCode){
        System.out.println(phone);
        System.out.println(checkCode);
        return "success";
    }

    //    get请求传递的是javaBean(传递的参数映射到java的一个对象中,在这里对象名与参数名的名字相同,个数相同,类型兼容)
    @GetMapping(value = "/getTest2")
    public String getTest2(Person person){
        System.out.println(person);
        return "success";
    }

前端发送post请求

axios.post('http://localhost:8080/register3',ruleForm).then((data) => {
        console.log(data);
    })

后端使用 @RequestBodyJSONObject

@RequestBody 接收前端传递给后端的json字符串

//   post请求 方法一
@PostMapping(value = "/register",produces = "application/json;charset=UTF-8")
    public String register(@RequestBody Person person){
    System.out.println(person);
    return "success";
}


//    post请求 方法2
@PostMapping(value = "/register2",produces = "application/json;charset=UTF-8")
    public String register2(@RequestBody JSONObject jsonObject) {
    String phone = jsonObject.getString("phone");
    String checkCode = jsonObject.getString("checkCode");
    System.out.println(phone);
    System.out.println(checkCode);
    return "success";
}

注:JSONObject爆红引入这个

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.9</version>
</dependency>