前端:Vue3
创建项目:
npm create vue@latest
> cd <your-project-name>
> npm install
> npm run dev
项目结构图如下:
1、查看入口文件内容:main.js
代码如下:
import './assets/main.css'
import { createApp } from 'vue'
import App from './App.vue'
import router from '@/router'
//import axios from 'axios'// console.log(App)
const app = createApp(App)
//app.config.globalProperties.$axios = axios
app.use(router)
// app.use(axios)app.mount('#app')
在main.js中,首先引入了Vue组件和APP根组件
2、APP跟组件代码如下:
<template><div id="app"><!-- App跟组件 --><router-view></router-view></div></template><script setup>name: 'app'
</script><style scoped></style>
3、路由文件配置:router/index.js
代码如下:
import { createRouter,createWebHistory } from 'vue-router'
import Login from '../components/Login.vue' //引用Login组件const routes = [{path: '/',redirect: '/login'},{path: '/login',component: Login}, //定义访问页面的路由地址]const router = createRouter({history:createWebHistory(),routes,
})export default router
4、Axios请求公共方法:utils/axios.js
代码如下:
import axios from 'axios'
//创建axios实例
const axiosInstance = axios.create({//api的BaseUrl baseURL : '/aa',setTimeout: 5000, //设置超时时间responseType: 'json',withDefaults : true, //是否允许带cookie这些headers: {'Content-Type' : 'application/json;charset=utf-8','x-token' : '777'}
});export default axiosInstance
5、测试消息页面:components/Login.vue
代码如下:
<template><header><img alt="Vue logo" class="logo" src="../assets/logo.svg" width="125" height="125" /><div class="wrapper">登录组件:{{ msg }}<button onclick="login"> axios</button></div></header></template><script>
import axiosInstance from '../utils/Axios'export default {data(){return {msg : '开始'}},mounted(){axiosInstance.get('login/login').then(response =>{//处理响应数据console.log(response.data);this.msg = response.data;}).catch(error =>{//处理错误消息console.error(error);})}}
</script><!-- 支持less语法格式 scoped代表样式只在本组件中起作用 lang="less" -->
<style scoped></style>
6、无代理情况向后端发请求会有跨域的问题:
代码如下:
import { fileURLToPath, URL } from 'node:url'import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'node:path'// https://vitejs.dev/config/
export default defineConfig({plugins: [vue(),],resolve: {alias: {'@': fileURLToPath(new URL('./src', import.meta.url))}},server: {proxy: {//需要代理的路径'/aa': {//目标服务器的地址target: 'http://localhost:9100/',//是否要将请求中的路径重写rewrite: path => path.replace(/^\/api/,''),//是否要改变代理的源地址changeOrigin: true,//其他可选的代理配置}}}
})
后端代码:
引入的jar包:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
测试代码:
@RestController
@RequestMapping("/login")
public class Login {@RequestMapping("/login")public String login(){return "登录成功";}
}