记录后端不同请求方式的接口,使用vue3框架下的前端axio请求不同写法

发布时间 2023-11-28 17:03:00作者: OriginCat

一.

后端接口:

    @GetMapping("/index")
    public ResponseResult index() {..}

 

前端接口:

indexInfo().then(res => {
    if (res.data.code == 200) {
        ElNotification({
            message: res.data.data.msg || "加载成功",
            type: 'success',
            duration: 2000
        })
        animArry.value = res.data.data.records;
        console.log(res.data.data.records)

    }
})

前端方法实现(将js函数整合在一个js文件中导入使用时):

export function indexInfo() {
  return axios.get("/t-animal/index")
}

二.

后端是get并使用Param注解携带参数

    @GetMapping(value = "/send")
    public ResponseResult code(@RequestParam("phone") String phone) {..}

 

const onSend = () => {
    const params = {
        phone: form.phone
    }
    axios.get('/send', { params }).then((res) => {
        console.log(res.data);
    })

}

三.

 

    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user, HttpServletResponse response) throws JsonProcessingException {..}

 

const onSubmit = () => {
    formRef.value.validate((valid) => {
        if (!valid) {
            return false
        }
        loading.value = true
        login(form.userName, form.password)
            .then(res => {
                console.log(res);
                if (res.data.code == 401) {
                    ElNotification({
                        message: res.data.msg || "登录失败",
                        type: 'warning',
                        duration: 2000
                    })
                } else if (res.data.code == 200) {
                    ElNotification({
                        message: res.data.msg || "登录成功",
                        type: 'success',
                        duration: 2000
                    })
                    setToken(res.data.data.token)
                    router.push("/")
                }
                //拿到请求成功的结果
            }).finally(()=>{
                loading.value = false
            })
    })
}

 

前端方法实现:

export function login(userName, password) {
  return axios.post("/user/login", {
    userName, password
  })
}

四.

后端是@RequestBody请求体

    public ResponseResult Declare(@RequestBody Declare declare) {..}

 

const onSubmit = () => {
    formRef.value.validate(async (valid) => {
        const resp = await axios.post('/t-animal/declare', declare2)
        if (resp.data.code == 200) {
            console.log('200');
        } else {
            console.log('error');
        }
        loading.value = false
    })
}

总结:
一共有以上几种请求方法:

Body:Post请求使用导入js文件,在组件中使用js实现两种方式.

Param请求使用Get请求,以及纯Get获取数据.