后端(springboot)
一、前后端分离结果包装类(Result)
package com.feng.common;
public class Result<T> {
private String code;
private String msg;
private T data;
public Result() {
}
public Result(T data) {
this.data = data;
}
public static Result success() {
Result result = new Result<>();
result.setCode("0");
result.setMsg("成功");
return result;
}
public static <T> Result<T> success(T data) {
Result<T> result = new Result<>(data);
result.setCode("0");
result.setMsg("成功");
return result;
}
public static Result error(String code, String msg) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
二、跨域工具类(CorsConfig)
package com.feng.common;
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 {
private static final long MAX_AGE = 24 * 60 * 60;
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setMaxAge(MAX_AGE);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
前端(vue)
一、使用vue-cli构建vue项目的跨域配置(vue.config.js)
// 跨域配置
module.exports = {
devServer: { //记住,别写错了devServer//设置本地默认端口 选填
port: 9876,
proxy: { //设置代理,必须填
'/api': { //设置拦截器 拦截器格式 斜杠+拦截器名字,名字可以自己定
target: 'http://localhost:9090/', //代理的目标地址
changeOrigin: true, //是否设置同源,输入是的
pathRewrite: { //路径重写
'/api': '' //选择忽略拦截器里面的单词
}
}
}
}
}
二、使用vite构建vue项目的跨域配置(vite.config.js)
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
const path = require('path')
export default defineConfig({
plugins: [vue()],
server: {
port: 9876,
proxy: {
'/api': {
target: 'http://192.168.154.100:9090/',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
},
resolve: {
alias: {
"@": path.resolve(__dirname, "src"),
"assets": path.resolve(__dirname, "src/assets"),
"components": path.resolve(__dirname, "src/components"),
"styles": path.resolve(__dirname, "src/styles"),
"plugins": path.resolve(__dirname, "src/plugins"),
"views": path.resolve(__dirname, "src/views"),
"layouts": path.resolve(__dirname, "src/layouts"),
"utils": path.resolve(__dirname, "src/utils"),
}
},
})
三、前后端分离包装结果工具集(request.js)
import axios from 'axios'
import router from "@/router";
const request = axios.create({
baseURL: "/api",
timeout: 5000
})
// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
request.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
// config.headers['token'] = user.token; // 设置请求头
//取出sessionStorage里面缓存 的用户信息 ,若空则需登录
let userJson = sessionStorage.getItem("user")
if (!userJson) {
router.push("/login")
}
return config
}, error => {
return Promise.reject(error)
});
// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
response => {
let res = response.data;
// 如果是返回的文件
if (response.config.responseType === 'blob') {
return res
}
// 兼容服务端返回的字符串数据
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
return res;
},
error => {
console.log('err' + error) // for debug
return Promise.reject(error)
}
)
export default request