JAVA后端跨域处理

博客介绍了跨域问题的解决方法,虽未详细说明方法内容,但围绕跨域展开,为解决跨域问题提供了思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法1:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @Description 全局跨域处理(测试环境或生产环境nginx配置跨域后, 服务端不应再设置跨域, 否则会出现两次跨域设置, 跨域不生效问题)
 * @Author lc
 * @Date 2019/6/26 0026 下午 3:07
 **/
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    /**
     * @return void
     * @Description 配置全局跨域处理
     * @Author lc
     * @Date 2019/6/26 0026 下午 3:10
     * @Param [registry]
     **/
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }
}

 

方法二:

import com.fendan.manager.dto.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletResponse;

/**
 * @Description //TODO
 * @Author lc
 * @Date 2019/6/26 0026 下午 3:24
 **/
public class TestController {

    @ApiOperation("跨域测试")
    @PostMapping(value = "/test")
    @Validated
    public Result test(HttpServletResponse response) {
        // 响应头设置
        response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept");
        // 指定允许其他域名访问
        response.addHeader("Access-Control-Allow-Origin", "*");
        // 响应类型
        response.addHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE");
        // 最大值设置
        response.addHeader("Access-Control-Max-Age", "1000");
        return null;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值