SpringBoot后端跨域-配置cors

cors

CORS,全称Cross-Origin Resource Sharing ,是一种允许当前域(domain)的资源被其他域(domain)的脚本请求访问的机制,通常由于同域安全策略(the same-origin security policy)浏览器会禁止这种跨域请求。

配置类CorsConfig

package com.base.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;

/**
 * @ClassName CorsConfig
 * @Decription
 * @Author Kalinda
 * @Date 2020/1/29 8:57
 * @Version 1.0
 **/
@Configuration
public class CorsConfig  {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}

测试controller

package com.base.cors.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName TestController
 * @Decription
 * @Author Kalinda
 * @Date 2020/1/29 9:02
 * @Version 1.0
 **/
@RestController
public class TestController {
    @RequestMapping("/test")
    public int test() {
        return 1;
    }
}

前端访问

<template>
  <div>
    <el-button plain @click="testCors">测试跨域</el-button>
  </div>
</template>

<script>
let baseUrl = 'http://localhost:8989'

export default {
  name: "TestCors",
  methods: {
    testCors() {
      this.$http({
        url: baseUrl + "/test",
        methods: "post",
      })
        .then(response => {
          console.log(response.data);
        })
        .catch(function(error) {
          console.log(error);
        });
    }
   }
 }

访问成功

访问成功啦

发布了23 篇原创文章 · 获赞 0 · 访问量 941

猜你喜欢

转载自blog.csdn.net/finally_flx/article/details/104104707
今日推荐