在 SpringBoot 中设置允许跨域请求(包含Vue代码)

1.前言

HTML5 支持了 CORS 协议。CORS 是一个 W3C 标准,全称是”跨域资源共享”(Cross-origin resource sharing),允许浏览器向跨源服务器,发出 XMLHttpRequest 请求,从而克服了 AJAX 只能同源使用的限制。它通过服务器增加一个特殊的 Header[Access-Control-Allow-Origin]来告诉客户端跨域的限制,如果浏览器支持 CORS、并且判断 Origin 通过的话,就会允许 XMLHttpRequest 发起跨域请求。

前端使用了 CORS 协议,就需要后端设置支持非同源的请求,对于SpringBoot 对于CORS 同样有着良好的支持,
首先附上官网地址:
https://docs.spring.io/spring-boot/docs/2.0.2.RELEASE/reference/htmlsingle/#boot-features-cors

2、后端增加代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.wangjikai.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
* 实现基本的跨域请求
* @author linhongcun
*
*/
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 允许任何头
corsConfiguration.addAllowedMethod("*"); // 允许任何方法(post、get等)
return corsConfiguration;
}

@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 对接口配置跨域设置
return new CorsFilter(source);
}
}

3.前端重要代码

axios.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import Vue from "vue";
import axios from "axios";

// 响应时间
axios.defaults.timeout = 600 * 1000;
Vue.prototype.$axios = axios;
// 配置cookie
// axios.defaults.withCredentials = true
// 配置请求头
// axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
// 静态资源
Vue.prototype.$static = "";
// 配置接口地址
//这里的接口地址是你地址的相同的前半部分,方便管理
// axios.defaults.baseURL = ''
// 发送请求
//post请求

if (process.env.NODE_ENV == "production") {

axios.defaults.baseURL = "";
//axios.defaults.baseURL = process.env.BASE_API;
} else {
//axios.defaults.baseURL = 'http://127.0.0.1:8088'
axios.defaults.baseURL = 'http://127.0.0.1:10002'
//axios.defaults.baseURL = "http://172.168.10.4:10002"
}

axios.interceptors.request.use(
config => {
try {
var userInfo = window.sessionStorage.getItem("userInfo");
if(userInfo){
let {loginname} = JSON.parse(userInfo)
config.headers.loginName = loginname
console.log("loginname",loginname);
console.log("config.headers",config.headers);
}
} catch (e) {
console.error(e)
}
return config
},
error => {
return Promise.reject(error)
}
)

export function post(url, params) {
return new Promise((resolve, reject) => {
// console.log(1)
// console.log()
axios
.post(axios.defaults.baseURL + url, params)
.then(
res => {
resolve(res.data);
},
err => {
reject(err.data);
}
)
.catch(err => {});
});
}
//get请求
export function get(url, params) {
return new Promise((resolve, reject) => {
axios
.get(axios.defaults.baseURL + url, {
params: params
})
.then(res => {
resolve(res.data);
})
.catch(err => {});
});
}
//get请求
export function exp(url, params) {
return new Promise((resolve, reject) => {
axios
.post(axios.defaults.baseURL + url, params, {
responseType: "blob"
})
.then(response => {
let fileName = window.decodeURI(
response.headers["content-disposition"].split("=")[1]
);
let link = document.createElement("a");
link.href = window.URL.createObjectURL(
new Blob([response.data], {
type:
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
})
);
link.target = "_blank";
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
});
}
export function baseUrl() {
return axios.defaults.baseURL;
}

写请求的js
req.js

1
2
3
4
5
6
7
import {
get,
post
} from '../utils/axios'
export function getAll() {//表格数据
return get(`/getAll`)
}

页面使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<script>
import {
getAll
} from "@/api/warehouse";


export default {
methods: {
getList(){
getAll()
.then(res => {
console.log(res);
})
.catch(error => {
console.log(error);
});
}

},
}
</script>
继开 wechat
欢迎加我的微信,共同交流技术