Vue3实战笔记(05)--- 跨域前后端解决方案

62 篇文章 2 订阅
62 篇文章 2 订阅


前言

跨域问题(Cross-Origin Resource Sharing, CORS)是由于浏览器的同源策略(Same-Origin Policy, SOP)限制导致的。同源策略是一种安全措施,它限制了一个源(域名、协议和端口)的文档或脚本如何与另一个源的资源进行交互。这种限制是为了防止恶意网站访问敏感数据。

一、跨域问题的表现

跨域问题通常表现为以下几种情况:

  • 无法从不同的源(域、协议或端口)加载样式表、图片、脚本等资源。
  • 无法向不同的源发送 AJAX 请求(使用 XMLHttpRequest 或 fetch)。
  • 无法读取从不同源加载的网页的某些属性或数据。

二、前端解决方案

由于本系列笔记是Vue实战项目,本文只阐述i常用的Vue项目相关的解决方案,还有其他方案请自行了解。
在vite.config.mts文件中配置代理:

  server: {
    port: 3000,
    proxy:{ //代理配置,解决跨域
      '/api':{
        target:'http://localhost:9203',  //获取路径中包含了api的请求
        changeOrigin:true,   //修改源
        rewrite:(path)=>path.replace(/^\/api/,'') //api替换为''
      }
    }
  },

原理是从浏览器访问时候的请求发到前端,再由前端代理发送到后端,避免了浏览器的跨域限制。配置代理后带有api的请求路径就会被拦截替换,例如:

axios.get("http://localhost:3000/api/hello")
.then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  

前端请求url:http://localhost:3000/api/hello
会被替换成http://localhost:9203/hello

三、后端解决方案(CORS):

CORS 是一种机制,它允许受限资源(如字体或 API 请求)在网页中被跨域访问。服务器需要在响应头中添加特定的 CORS 头部信息来表明它允许哪些来源的站点访问其资源。
1、注解(只能控制一个controller)

  @RestController
  @CrossOrigin//跨域
  public class TestController {

    @GetMapping(value = "/hello")
    public String hello() {
      System.out.println(123);
      return "Hello";
    }
 }

2、 配置 CORS 解决跨域

/**
 * @Author:shanhua
 * @Package:site.shanhua.admin.auth.config
 * @Project:shanhuaadmin
 * @name:MyWebConfigurer
 * @Date:2024/2/5 18:59
 * @Filename:MyWebConfigurer
 */
@Configuration
public class MyWebConfigurer implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry corsRegistry){
        /**
         * 所有请求都允许跨域,使用这种配置就不需要
         * 在interceptor中配置header了
         */
        corsRegistry.addMapping("/**")
                .allowCredentials(true)
                .allowedOriginPatterns("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .allowedHeaders("*")
                .maxAge(3600);
    }

}

3、通过 CorsFilter 解决跨域

/**
 * @Author:shanhua
 * @Package:site.shanhua.admin.auth.config
 * @Project:shanhuaadmin
 * @name:CorsConfig
 * @Date:2024/2/5 18:45
 * @Filename:CorsConfig
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOriginPattern("*");
        config.setAllowCredentials(true);
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);
        return new CorsFilter(configSource);
    }

}

4、通过yaml配置gateway

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
        # 仅在开发环境设置为*
          '[/**]':
            allowedOrigins: "*"
            allowedHeaders: "*"
            allowedMethods: "*"

四、其他解决方案

通过 nginx 配置 CORS 解决跨域

//所有域名

server {
    ...
    location / {
        #允许 所有头部 所有域 所有方法
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Headers' '*';
        add_header 'Access-Control-Allow-Methods' '*';
        #OPTIONS 直接返回204
        if ($request_method = 'OPTIONS') {
            return 204;
        }
    }
    ...
}

//指定域名

map $http_origin $corsHost {
    default 0;
    "~https://aa.cn" https://aa.cn;
    "~https://bb.cn" https://bb.cn;
    "~https://cc.cn" https://cc.cn;
}
server {
    ...
    location / {
        #允许 所有头部 所有$corsHost域 所有方法
        add_header 'Access-Control-Allow-Origin' $corsHost;
        add_header 'Access-Control-Allow-Headers' '*';
        add_header 'Access-Control-Allow-Methods' '*';
        #OPTIONS 直接返回204
        if ($request_method = 'OPTIONS') {
            return 204;
        }
    }
    ...
}

总结

浏览器跨域问题是由同源策略引起的,有多种方法可以解决这个问题。选择哪种方法取决于具体的场景、需求以及服务器的配置情况。CORS 是最标准化和安全的方式,但可能需要后端开发者的配合。其他方法可能在特定情况下更为方便,但可能不如 CORS 安全。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值