1. Spring Boot
创建Spring Boot工程。后端提供接口给前端请求,从数据库中获取数据。
后端项目结构
重点是需要跨域的支持
@Component
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Credentials", "true");
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
response.getWriter().println("ok");
return;
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
2. Vue
安装vue-cli
npm install --g vue-cli
打开Vue的可视化管理工具界面
vue ui
2.1 创建项目
选择手动,并选择Router和Vuex,取消Linter
勾选history mode
创建项目,可选是否保留成预设。
生成的项目结构
2.2 前端项目
前端项目结构
引入axios
npm install axios --save
request.js
创建 axios 实例
import axios from 'axios'
const service = axios.create({
baseURL: 'http://localhost:8123/vue',
// 请求超时时间
timeout: 15000
})
export {
service as axios
}
userService.js
引入封装好的 axios 请求,编写调用的后端接口
import { axios } from '@/utils/request'
export function getByUsername (parameter) {
return axios.get('/user/getByUsername', { params: parameter })
}
User.vue
<template>
<div>
<input v-model="username" placeholder="username">
<button @click="getUserInfoByUsername()">搜索</button>
<pre>{{ userInfo }}</pre>
</div>
</template>
<script>
import { getByUsername } from "../api/userService";
export default {
name: "User",
data () {
return {
username: "",
userInfo: {}
}
},
methods: {
getUserInfoByUsername() {
const _this = this
const param = {
username: _this.username
}
getByUsername(param).then(res => {
_this.userInfo = res.data
})
}
}
}
</script>
修改router文件夹下index.js
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
},
{
path: '/user',
name: 'User',
component: () => import(/* webpackChunkName: "about" */ '../views/User.vue')
}
]
修改App.vue
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link> |
<router-link to="/user">User</router-link>
3. 测试
启动后端,启动前端 npm run serve
参考:
Spring Boot 系列:处理跨域请求
超详细!4小时开发一个SpringBoot+vue前后端分离博客项目!!
Springboot Vue Login(从零开始实现Springboot+Vue登录)