最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】给java的spring boot中后端加上CORS支持

Java crifan 1505浏览 0评论
折腾:
【未解决】vuejs中调用本地localhost的api报错:Access to XMLHttpRequest at from origin has been blocked by CORS policy
期间,去给spring boot的java后端加上CORS支持
java spring boot CORS
Getting Started | Enabling Cross Origin Requests for a RESTful Web Service
import org.springframework.web.bind.annotation.CrossOrigin;
好像只能允许http://localhost:9000的CrossOrigin
不能全部支持?
Getting Started | Enabling Cross Origin Requests for a RESTful Web Service
CORS support in Spring Framework
直接用:
@CrossOrigin
即可
@RestController
@RequestMapping("/account")
public class AccountController {


    @CrossOrigin
    @GetMapping("/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }
另外可以全局Class级别加上CrossOrigin
@CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
CORS support in Spring Framework
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
          registry.addMapping("/**");
    }
}
去找找
此处自己的WebConfig
SpringBoot 实现前后端分离的跨域访问(CORS) | Spring For All
  • * 方式1:返回新的CorsFilter
  • * 方式2:重写WebMvcConfigurer
  • * 方式3:使用注解(@CrossOrigin)
  • * 方式4:手工设置响应头(HttpServletResponse )
注:
CorsFilter / WebMvcConfigurer / @CrossOrigin 需要SpringMVC 4.2 以上的版本才支持
对应SpringBoot 1.3 版本以上都支持这些CORS特性
先去试试局部跨域是否有效
有空再试试 全局跨域
此处已有代码是:
@RequestMapping(path="/iec104") // This means URL's start with / (after Application path)
public class IEC104Controller {
    private static Logger logger = LoggerFactory.getLogger(IEC104Controller.class.getName());


  @Autowired // This means to get the bean called userRepository
         // Which is auto-generated by Spring, we will use it to handle the data
  private IEC104Repository iec104Repository;


  @PostMapping(path="/add") // Map ONLY POST Requests
  // public @ResponseBody String addNewIEC104 (
  public @ResponseBody IEC104 addNewIEC104 (
            // @RequestParam String data
          // @RequestParam String data,
          // @RequestParam String parseResult
          @RequestBody Map<String, Object> payload
      ) {
有前面提到的@Controller
去加上试试
import org.springframework.web.bind.annotation.CrossOrigin;

@Controller // This means that this class is a Controller
@CrossOrigin
springboot系列文章之实现跨域请求(CORS) – 掘金
然后重新编译
mvn clean package
java -jar target/xxx-0.0.1-SNAPSHOT.jar
然后再去vuejs中测试,就可以了。
【总结】
此处给java的spring boot的后端添加CORS支持:
是给@Controller加上:@CrossOrigin
@Controller // This means that this class is a Controller
@CrossOrigin
@RequestMapping(path="/iec104") // This means URL's start with / (after Application path)
public class IEC104Controller {
...
即可。
关于原理,详见:
SpringBoot 实现前后端分离的跨域访问(CORS) | Spring For All

转载请注明:在路上 » 【已解决】给java的spring boot中后端加上CORS支持

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.181 seconds, using 22.20MB memory