vue3.0:使用axios访问后台接口

添加依赖:axios和vue-axios

在package.json中显示为:

"dependencies": {
  "axios": "^0.21.1",
  "core-js": "^3.6.5",
  "element-plus": "^1.0.2-beta.28",
  "less": "^4.1.1",
  "less-loader": "^10.0.1",
  "vue": "^3.0.0",
  "vue-axios": "^3.2.4",
  "vue-router": "^4.0.0-0"
},

配置main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import installElementPlus from './plugins/element'
import './assets/css/global.css'
import axios from 'axios'

const app = createApp(App)
app.config.globalProperties.$axios = axios
axios.defaults.baseURL = "http://localhost:8088" //后端地址
installElementPlus(app)
app.use(router).mount('#app')

后端接口为(springboot):

package com.example.backproject.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @RequestMapping("/test")
    public String test(){
        return "test my test controller";
    }
}

在前端需要访问后端接口的地方写:

const {
  data: res
} = await this.$axios.post("test");
console.log(res);

即可在控制台打印:

在这里插入图片描述

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐