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

61 篇文章 1 订阅
61 篇文章 0 订阅


前言

跨域问题(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 安全。

  • 17
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
前后端分离的开发模式下,前端和后端是独立的两个系统,前端向后端发送请求时,常常会遇到跨域问题。为了解决这个问题,我们可以在后端进行跨域配置,也可以在前端进行跨域请求。 1. 后端跨域配置 在后端,可以使用 Spring Boot、Node.js、Django 等框架,在配置文件中增加跨域配置,比如在 Spring Boot 中,可以在 application.properties 或 application.yml 中增加以下配置: ``` # 允许所有域名跨域访问 spring.mvc.crossorigin.allowed-origins=* ``` 2. 前端跨域请求 在前端,可以使用以下几种方式解决跨域问题: 2.1 代理请求 通过在前端配置代理服务器,将前端的请求转发到后端服务器上,从而避免跨域问题。比如在 Vue.js 中,可以使用 vue-cli-service 的 proxyTable 配置实现代理请求: ``` // vue.config.js module.exports = { devServer: { proxy: { // 将请求转发到后端服务器上 '/api': { target: 'http://localhost:8080', changeOrigin: true, pathRewrite: { '^/api': '' } } } } } ``` 2.2 JSONP 请求 JSONP 请求是一种利用 script 标签的跨域技术,通过在前端页面中动态创建 script 标签,然后在后端返回一个 JSONP 回调函数,前端就可以获取到后端数据了。比如在 Vue.js 中,可以使用 axios-jsonp 库实现 JSONP 请求: ``` // 安装 axios-jsonp 库 npm install axios-jsonp --save // 使用 axios-jsonp 库发送 JSONP 请求 import axiosJsonp from 'axios-jsonp'; axios({ url: 'http://example.com', adapter: axiosJsonp }) .then(response => { console.log(response); }) .catch(error => { console.error(error); }); ``` 2.3 CORS 请求 CORS 请求是一种支持跨域的 HTTP 请求,前端可以在请求头中增加 Origin 字段,后端可以在响应头中增加 Access-Control-Allow-Origin 字段,从而允许跨域请求。比如在 Vue.js 中,可以使用 axios 库发送 CORS 请求: ``` // 使用 axios 库发送 CORS 请求 axios({ method: 'get', url: 'http://example.com', headers: { 'Origin': 'http://localhost:8080' } }) .then(response => { console.log(response); }) .catch(error => { console.error(error); }); ``` 以上是解决前后端分离跨域问题的几种方案,具体选择哪种方案需要根据项目实际情况来决定。需要注意的是,在使用代理请求时,应该避免将代理服务器暴露在公网上,以避免安全问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值