springboot跨域问题(Tomcat部署)

package com.example.test1.config;

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("http://127.0.0.1:8089"); // 1 设置访问源地址
        corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
        corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
        corsConfiguration.setMaxAge(MAX_AGE);
        source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }
}

vue+springboot会遇到的跨域问题。

vue与springboot都需要设置跨域

否则在Tomcat无法运行(报资源屏蔽错误)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot跨域问题可以通过配置来解决。下面是一种常见的解决方法: 在 Spring Boot 项目中,可以使用 `@CrossOrigin` 注解来处理跨域问题。这个注解可以直接添加在 Controller 类或者方法上,用于指定允许跨域的源。 示例代码如下: ```java @RestController @CrossOrigin(origins = "http://example.com") public class MyController { @GetMapping("/api/data") public String getData() { // 处理请求 return "data"; } } ``` 在上述示例中,`@CrossOrigin(origins = "http://example.com")` 指定了允许跨域访问的源,即来自 http://example.com 的请求可以跨域访问该接口。 如果需要允许多个源进行跨域访问,可以使用数组形式指定多个源,如: ```java @CrossOrigin(origins = {"http://example.com", "http://another-domain.com"}) ``` 此外,还可以通过全局配置方式解决跨域问题。在 Spring Boot 项目的配置类中添加如下配置: ```java @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://example.com") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("*") .allowCredentials(true) .maxAge(3600); } } ``` 上述配置中,`allowedOrigins` 指定允许跨域访问的源,`allowedMethods` 指定允许的请求方法,`allowedHeaders` 指定允许的请求头,`allowCredentials` 表示是否允许发送身份凭证(如 cookie),`maxAge` 指定预检请求的有效期。 这是一种常见的解决 Spring Boot 跨域问题的方法,你可以根据实际情况选择适合的方式来解决跨域问题

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿木小纸条

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值