前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java Vue 前后端跨域解决方案

Java Vue 前后端跨域解决方案

作者头像
白衣少年
发布2024-06-06 09:37:56
880
发布2024-06-06 09:37:56
举报

Java Vue 前后端跨域解决方案

项目是后端SpringBoot整合MyBatis 前端Vue+axios

事情起因,因为公司目前有些东西很每天录数据很麻烦,所以打算自己给公司写一个库存管理的项目,可是在写好接口后,前端封装完axios后请求接口时出现了岔子,居然 跨域 了!!!!😭

错误截图

解决方案【后端】

给Java代码添加过滤器,使其能够跨域请求,代码如下

代码语言:javascript
复制
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 CorsConfiguration Buildconfig() {
        // 创建一个CorsConfiguration对象
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许所有域模式
        corsConfiguration.addAllowedOriginPattern("*");
        // 暴露所有头部
        corsConfiguration.addExposedHeader("*");
        // 允许凭据
        corsConfiguration.setAllowCredentials(true);
        // 允许所有方法
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }
    @Bean
    public CorsFilter corsFilter(){
        UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
        // 注册CorsConfiguration配置到source中
        source.registerCorsConfiguration("/**", Buildconfig());
        return new CorsFilter(source);
    }
}

效果

请求成功!!!完美解决!!!

文章末尾【分享下我的axios封装】

代码语言:javascript
复制
import axios from "axios";
// const Api_URL='http://localhost:3000'
const Api_URL = 'http://localhost:8080'



// 请求头设置
// axios.defaults.headers.common['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36';

const instance = axios.create({
  Api_URL,
  timeout: 6000,
  withCredentials:true,
  changeOrigin: true,
  // headers: {'X-Custom-Header': 'foobar'} 设置请求头就会跨域报错!!!所以注销了
});

//axios 超时时间
axios.defaults.timeout = 10000;
axios.defaults.withCredentials=true;

// 请求拦截器
instance.interceptors.request.use((config) => {
  // if (localStorage._token) {
  //   config.headers.Authorization = localStorage._token;
  // }
  return config;
},function (error) {
    return Promise.reject(error)
});

//响应拦截器
instance.interceptors.response.use(
    (res) => {
      return res;
    },
    (error) => {
      // 错误状态码处理
      if (error.response) {
        let {status} = error.response
        switch (status) {
          case 404:
            message.error(error.response.message)
            break
          case 500:
            message.error(error.response.statusText)
            break
        }
      }
      return Promise.reject(error);
    }
);


const http = {
  /** get 请求
   * @param  {接口地址} url
   * @param  {请求配置} config
   */
  async get(url, config) {
    return new Promise((resolve, reject) => {
      instance
          .get(Api_URL + url, {params: config})
          .then((response) => {
            if (response) resolve(response.data);
          })
          .catch((error) => {
            reject(error);
          });
    });
  },
  /** post 请求
   * @param  {接口地址} url
   * @param  {请求数据} data
   * @param  {配置} config
   */
  async post(url, data, config) {
    return new Promise((resolve, reject) => {
      instance
          .post(Api_URL + url, data, config)
          .then((response) => {
            console.log(response);
            if (response) resolve(response.data);
          })
          .catch((error) => {
            reject(error);
          });
    });
  },
  /** delete 请求
   * @param  {接口地址} url
   * @param  {请求配置} config
   */
  async delete(url, config) {
    return new Promise((resolve, reject) => {
      instance
          .delete(Api_URL + url, {
            data: config,
          })
          .then((response) => {
            if (response) resolve(response.data);
          })
          .catch((error) => {
            reject(error);
          });
    });
  },

  /** put 请求
   * @param  {接口地址} url
   * @param  {请求配置} config
   */
  async put(url, config) {
    return new Promise((resolve, reject) => {
      instance
          .put(Api_URL + url, config)
          .then((response) => {
            if (response) resolve(response.data);
          })
          .catch((error) => {
            reject(error);
          });
    });
  },
};

export default http;
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024年04月21日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Java Vue 前后端跨域解决方案
  • 错误截图
  • 解决方案【后端】
  • 效果
  • 文章末尾【分享下我的axios封装】
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档