When the frontend accesses a backend method
created() {
//请求分页数据
fetch("http://localhost:9090/user/page?pageNum=1&pageSize=2").then(res => res.json()).then(res => {
console.log(res)
})
}
A cross-domain error will occur:
Access to fetch at 'http://localhost:9090/user/page?pageNum=1&pageSize=2' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Due to different port numbers, browser cross-domain errors are triggered. There are two processing methods at this time, one is background processing (recommended), and the other is front-end processing.
1. Back-end processing method
Add the package config to the project and create the java file Corsconfig.java under config with the following content:
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;
@Configuration
public class CorsConfig {
// 当前跨域请求最大有效时长。这里默认1天
private static final long MAX_AGE = 24 * 60 * 60;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
corsConfiguration.setMaxAge(MAX_AGE);
source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
}
2. Front-end processing method
Create the utils folder and create the permission.js file under the folder
import router from "@/router";
import Layout from "@/layout/Layout";
// 注意:这个文件是设置动态路由的
// permissions是一个资源的数组
export function activeRouter() {
const userStr = sessionStorage.getItem("user")
if (userStr) {
const user = JSON.parse(userStr)
let root = {
path: '/',
name: 'Layout',
component: Layout,
redirect: "/home",
children: []
}
user.permissions.forEach(p => {
let obj = {
path: p.path,
name: p.name,
component: () => import("@/views/" + p.name)
};
root.children.push(obj)
})
if (router) {
router.addRoute(root)
}
}
}