Java Vue 前后端跨域解决方案

白衣少年
2024-04-21 / 0 评论 / 7 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2024年04月22日,已超过12天没有更新,若内容或图片失效,请留言反馈。

Java Vue 前后端跨域解决方案

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

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

错误截图 表情

Snipaste_2024-![Snipaste_2024-04-21_21-36-18.png
Snipaste_2024-04-21_21-36-24.png

解决方案【后端】

给Java代码添加过滤器,使其能够跨域请求,代码如下
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);
    }
}

效果

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

Snipaste_2024-04-21_21-44-30.png

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

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;
2

打赏

评论 (0)

OwO
取消