You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue通过Axios调用Spring接口遇CORS跨域错误,求解决

解决Vue+Axios调用Spring后端的CORS跨域错误

核心问题

浏览器拦截了跨域请求,因为Spring后端没有返回Access-Control-Allow-Origin响应头,导致请求被CORS策略阻止。以下是具体解决步骤:


一、Spring后端配置(推荐全局配置)

方式1:全局CORS过滤器(覆盖所有接口)

创建CORS配置类,统一处理跨域规则:

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 {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 允许前端域名,生产环境替换为实际前端地址,也可暂时用"*"允许所有(不推荐生产用)
        config.addAllowedOrigin("http://localhost:8080");
        // 允许所有HTTP请求方法(GET/POST/PUT等)
        config.addAllowedMethod("*");
        // 允许所有请求头
        config.addAllowedHeader("*");
        // 允许携带Cookie(如果需要前后端共享Cookie)
        config.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 对所有接口路径生效
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

方式2:控制器/方法级局部配置

如果只需要给特定接口开跨域,用@CrossOrigin注解:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
// 给整个控制器下的接口开跨域
@CrossOrigin(origins = "http://localhost:8080", allowCredentials = "true")
public class TestController {
    @GetMapping("/api/hello")
    // 也可以单独给某个方法加注解
    // @CrossOrigin(origins = "http://localhost:8080")
    public String getHello() {
        return "Spring后端响应内容";
    }
}

二、Vue前端配置(两种可选方案)

方案1:开发环境代理转发(无需后端改CORS)

修改vue.config.js,通过前端代理将请求转发到后端,避免浏览器跨域校验:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    proxy: {
      // 匹配所有以/api开头的请求
      '/api': {
        target: 'http://localhost:8081', // 后端服务的实际地址+端口
        changeOrigin: true, // 开启跨域代理
        pathRewrite: {
          '^/api': '' // 如果后端接口没有/api前缀,就把前端的/api前缀去掉
        }
      }
    }
  }
})

然后Axios请求用相对路径:

import axios from 'axios'

export default {
  mounted() {
    axios.get('/api/hello')
      .then(res => {
        console.log('后端响应:', res.data)
      })
      .catch(err => console.error('请求失败:', err))
  }
}

方案2:直接请求后端(需后端已配置CORS)

如果后端已经配好CORS,直接设置Axios的baseURL:

import axios from 'axios'

// 全局设置后端地址
axios.defaults.baseURL = 'http://localhost:8081'
// 如果需要携带Cookie,开启这个配置
axios.defaults.withCredentials = true

export default {
  mounted() {
    axios.get('/api/hello')
      .then(res => console.log(res.data))
  }
}

注意事项

  1. 如果后端设置了allowCredentials = true,前端必须同时开启withCredentials: true,且不能用*作为允许的源,必须指定具体域名。
  2. 生产环境禁止用*允许所有源,要替换为实际的前端域名(如https://your-frontend.com)。
  3. 检查后端服务是否正常启动,端口和配置中的地址是否一致。

内容的提问来源于stack exchange,提问作者jun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 17:40:41