zoukankan      html  css  js  c++  java
  • SpringBoot解决cors跨域问题

    1.使用@CrossOrigin注解实现
     (1).对单个接口配置CORS

    1 @CrossOrigin(origins = {"*"})
    2 @PostMapping("/hello")
    3 @ResponseBody
    4 public ResultVO hello() {
    5     return new ResultVO(1,"成功");
    6 }

     (2).对某个Controller下的所有接口配置CORS

    @CrossOrigin
    @Controller
    public class HelloController {
    
    }

    2.配置全局的CORS

    (1)添加配置类

     1 package com.yltx.api.config;
     2 
     3 import org.springframework.context.annotation.Bean;
     4 import org.springframework.context.annotation.Configuration;
     5 import org.springframework.web.cors.CorsConfiguration;
     6 import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
     7 import org.springframework.web.filter.CorsFilter;
     8 
     9 /**
    10  * @Author: Hujh
    11  * @Date: 2019/5/9 15:49
    12  * @Description: Cors跨域配置
    13  */
    14 @Configuration
    15 public class CorsConfig {
    16     @Bean
    17     public CorsFilter corsFilter() {
    18         final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
    19         final CorsConfiguration corsConfiguration = new CorsConfiguration();
    20         corsConfiguration.setAllowCredentials(true);
    21         corsConfiguration.addAllowedOrigin("*");
    22         corsConfiguration.addAllowedHeader("*");
    23         corsConfiguration.addAllowedMethod("*");
    24         urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
    25         return new CorsFilter(urlBasedCorsConfigurationSource);
    26     }
    27 }

    (2)添加配置类

     1 import org.springframework.context.annotation.Configuration;
     2 import org.springframework.web.servlet.config.annotation.CorsRegistry;
     3 import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
     4 
     5 /**
     6  * @Author: Hujh
     7  * @Date: 2019/5/9 16:18
     8  * @Description:
     9  */
    10 @Configuration
    11 public class WebMvcConfig extends WebMvcConfigurationSupport {
    12     @Override
    13     public void addCorsMappings(CorsRegistry registry) {
    14         registry.addMapping("/**")
    15                 .allowedOrigins("*")
    16                 .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
    17                 .maxAge(3600)
    18                 .allowCredentials(true);
    19     }
    20 }

    注:添加配置类方法取一即可.

  • 相关阅读:
    C++ 派生类成员的访问属性
    C++ 继承和派生介绍
    CSAPP lab2 二进制拆弹 binary bombs phase_5
    C++ new和delete 堆和栈
    Substrings (C++ find函数应用)
    CSAPP lab2 二进制拆弹 binary bombs phase_4
    CSAPP lab2 二进制拆弹 binary bombs phase_3
    C++ 实验 使用重载运算符实现一个复数类
    C++ 操作符重载
    UVALive 4877 Non-Decreasing Digits 数位DP
  • 原文地址:https://www.cnblogs.com/hujunhui/p/10839175.html
Copyright © 2011-2022 走看看