跨域问题记录:has been blocked by CORS policy_ The ‘Access-Control-Allow-Origin‘

一般出现的问题:

has been blocked by CORS policy: The ‘Access-Control-Allow-Origin’

问题原因:

跨域:指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对 javascript 施加的安全限制。

同源策略:是指协议,域名,端口都要相同,其中有一个不同都会产生跨域(重点:浏览器产生了跨域)

问题截图:
在这里插入图片描述
在这里插入图片描述

以上两张图片就是浏览器报错出现的跨域问题,但问题点又不一样:第一张图是未设置跨域,第二张图是设置了多重跨域,所以无论前端还是后端都只能设置一层跨域

解决方案:

  1. 前端以vue为例(一般后端解决跨域问题比较方便,这样当项目部署到服务器上的时候也不会很麻烦),要在本地开发时,前端可以在项目中的vue.config.js中进行配置,相关示例如下:
  devServer: {
    // development server port 8000
    port: 8000,
    // If you want to turn on the proxy, please remove the mockjs /src/main.jsL11
    proxy: {
      '/api': {
        target: 'http://192.168.92.11',
        ws: false,
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''                    
        }
      },
  },
  1. 后端设置(重点:只能设置一层跨域)

(1)网关统一配置跨域


@Configuration
public class GulimallCorsConfiguration {
    /**
     * 功能描述:网关统一配置允许跨域
     *
     * @author cakin
     * @date 2020/10/25
     * @return CorsWebFilter 跨域配置过滤器
     */
    @Bean
    public CorsWebFilter corsWebFilter(){
        // 跨域配置源
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 跨域配置
        CorsConfiguration corsConfiguration = new CorsConfiguration();
 
        // 1 配置跨域
        // 允许所有头进行跨域
        corsConfiguration.addAllowedHeader("*");
        // 允许所有请求方式进行跨域
        corsConfiguration.addAllowedMethod("*");
        // 允许所有请求来源进行跨域
        corsConfiguration.addAllowedOrigin("*");
        // 允许携带cookie进行跨域
        corsConfiguration.setAllowCredentials(true);
        // 2 任意路径都允许第1步配置的跨域
        source.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsWebFilter(source);
    }
}

(2)服务内设置跨域:注解@CrossOrigin

@RestController
@RequestMapping("/account")
public class AccountController {

    @CrossOrigin
    @GetMapping("/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

    @DeleteMapping("/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}

对于跨域还有其他解决方案,重要的是要知道出现问题的原因以及搜索问题的思路

猜你喜欢

转载自blog.csdn.net/weixin_45680024/article/details/127311020
今日推荐