vue+Spring Boot跨域需要前后端一起操作
前端:
requestURLAxios.ts
import { ref } from "vue";
import axios from "axios";
//这里一行什么意思我也不知道,网上抄的(我的理解是后端地址暂时写一下而已,因为后面我们会替换的)
axios.defaults.baseURL = '/api';
//post方法
//url是后端地址,data是前端往后端发的数据
export function postUrlAxios(url: string, data:string) {
const result = ref(null); //后端发过来的数据
const loading = ref(true); //加载中
const loaded = ref(false); //加载完成了没有
const error = ref(null); //报错
axios
.post(url, {
data,
})
.then((res) => {
loading.value = false;
loaded.value = true;
result.value = res.data;
})
.catch((e) => {
error.value = e;
console.log(`请求服务器失败!${e}`);
loading.value = false;
});
return {
result,
loading,
loaded,
error,
};
}
//get方法
export function getUrlAxios(url: string) {
const result = ref(null); //后端发过来的数据
const loading = ref(true); //加载中
const loaded = ref(false); //加载完成了没有
const error = ref(null); //报错
axios
.get(url)
.then((res) => {
loading.value = false;
loaded.value = true;
result.value = res.data;
})
.catch((e) => {
error.value = e;
console.log(`请求服务器失败!${e}`);
loading.value = false;
});
return {
result,
loading,
loaded,
error,
};
}
serviceAPI.config.ts
import { postUrlAxios } from "@/hooks/requestURLAxios";
//给后台发送登录数据
export const loginServer = (data:string) => postUrlAxios("url", data);
在package.json同目录下新建vue.config.js
vue.config.js
module.exports = {
devServer: {
proxy: {
"/api": {
// 此处的写法,目的是为了 将 /api 替换成 http://localhost:8001/login/
target: "http://localhost:8001/login/",
// 允许跨域
changeOrigin: true,
ws: true,
pathRewrite: {
"^/api": "",
},
},
},
},
};
登录页面
Login.vue
<template>
<!-- 导航栏 -->
<TopNav />
<!-- 导航栏底色 -->
<div style="height: 2.7rem; background-color: #fff"></div>
<!-- 主要内容 -->
<div class="main">
<!-- 登录页面主体 start -->
<div class="login-body">
<span>登录</span>
<!-- 用户名 -->
<div class="field">
<input type="text" placeholder="请输入用户名" v-model="username" />
</div>
<!-- 密码 -->
<div class="field">
<input type="password" placeholder="请输入密码" v-model="password" />
</div>
<!-- 记住密码 -->
<div class="field-check">
<input
type="checkbox"
class="checkbox"
id="remberpwd"
value="记住密码"
v-model="remberpwd"
/>
<label class="checkbox-lable" for="remberpwd">记住密码</label>
</div>
<!-- 登录按钮 -->
<button class="login" @click="login">登录</button>
</div>
</div>
</template>
<script lang="ts">
import { onMounted, reactive, toRefs, watch } from "vue";
import TopNav from "@/components/TopNav.vue";
import { loginServer } from "@/serviceAPI.config";
//引入路由
import { useRouter } from "vue-router";
interface stateProps {
username: string | null;
password: string | null;
remberpwd: boolean;
}
export default {
name: "app",
setup() {
const state: stateProps = reactive({
username: null, //用户名
password: null, //密码
remberpwd: false, //记住密码
});
const router = useRouter();
// 页面初始化时,赋值用户名密码
onMounted(() => {
console.log(localStorage);
if (localStorage.getItem("username")) {
state.username = localStorage.getItem("username");
state.password = localStorage.getItem("password");
state.remberpwd = true;
}
});
// 记住密码
watch(
() => state.remberpwd,
(val: boolean) => {
remberPassword(val);
}
);
//记住密码
const remberPassword = (val: boolean) => {
if (val === true && state.username != null && state.password != null) {
localStorage.setItem("username", state.username);
localStorage.setItem("password", state.password);
} else {
localStorage.removeItem("username");
localStorage.removeItem("password");
}
};
// 验证用户名密码
const login = () => {
const data = {
"user":state.username,
"password": state.password,
};
// result是从服务器获得的数据
const { result } = loginServer(JSON.stringify(data));
console.log("json数据:" + JSON.stringify(data));
console.log('result:' + result.value);
//记住密码
// remberPassword(state.username)
if (result.value == true) {
//跳转到后台
router.push('/backstage')
} else {
alert("用户名或者密码错误");
}
};
return {
...toRefs(state),
login,
};
},
components: {
TopNav,
},
};
</script>
<style scoped>
.main {
width: 980px;
margin: 0 auto;
margin-top: 250px;
height: auto;
display: flex;
justify-content: center;
align-items: center;
text-align: center;
}
/**主体内容 */
.login-body {
margin: 0 auto;
margin-top: -20px;
width: 50%;
background: #ffffff;
box-shadow: 0px 10px 20px rgba(0, 0, 0, 0.1);
opacity: 1;
border-radius: 10px;
padding: 20px 0;
height: calc(100% - 200px);
}
.field {
width: 70%;
margin: 0 auto;
margin-top: 30px;
border-bottom: 1px solid rgb(204, 203, 203);
/* 图标输入框对齐 */
display: flex;
align-items: center;
padding: 5px 0;
}
.field input {
border: 0;
width: 100%;
font-size: 13px;
}
input::-webkit-input-placeholder {
color: rgba(0, 0, 240, 0.5);
font-size: 13px;
}
input:focus {
/* 边框不用border,用outline */
outline: 0px;
}
/* 多选框 */
.field-check {
margin: 0 auto;
margin-top: 10px;
width: 70%;
text-align: right;
}
.checkbox-lable {
padding-left: 5px;
cursor: pointer;
margin: 0;
vertical-align: middle;
font-size: 13px;
}
.checkbox {
display: inline-block;
vertical-align: middle;
margin-bottom: 2px;
}
/* css 复选框 */
input[type="checkbox"] {
cursor: pointer;
position: relative;
}
input[type="checkbox"]::after {
position: absolute;
top: 0;
background-color: #fff;
color: #fff;
width: 14px;
height: 14px;
display: inline-block;
visibility: visible;
padding-left: 0px;
text-align: center;
content: " ";
border-radius: 2px;
box-sizing: border-box;
border: 1px solid #ddd;
}
input[type="checkbox"]:checked::after {
content: "";
background-color: rgba(94, 94, 233, 0.5);
/* border-color: rgba(94, 94, 233, 0.5); */
}
input[type="checkbox"]:checked::before {
content: "";
position: absolute;
top: 1px;
left: 5px;
width: 3px;
height: 8px;
border: solid white;
border-width: 0 2px 2px 0;
transform: rotate(45deg);
z-index: 1;
}
/* 登录按钮 */
.login {
width: 70%;
margin-top: 30px;
border: 0px;
height: 40px;
border-radius: 10px;
background: rgba(0, 0, 240, 0.5);
color: #ffffff;
}
button:focus {
/* 边框不用border,用outline */
outline: 0px;
}
</style>
后端(不全,只写了配置跨域部分,其他你们自己写吧)
在springboot后端:
config文件夹下(没有的新建就好)
添加class文件CORSConfig.java
CORSConfig.java
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @Description 跨域配置
* @Author hejiang
* @Date 2021/4/29 13:31
**/
@Configuration
public class CORSConfig extends WebMvcConfigurerAdapter{
static final String ORIGINS[] = new String[] { "GET", "POST", "PUT", "DELETE" };
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS)
.maxAge(3600);
}
}
另一个文件:CORSFilter
内容如下:
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CORSFilter implements Filter {
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);
}
public void destroy() {
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
然后再控制类中加上注解
@CrossOrigin