解决前后端分离开发前端在请求后台数据时候的跨域请求(403)问题(已解决)

时间:2025-03-23 12:44:05

解决前后端分离开发前端在请求后台数据时候的跨域请求(403)问题(已解决)

问题描述

在进行前后端分离开发的时候,前端发送请求到后台进行数据的请求总是提示请求出错。在debug模式下查看网络请求情况提示请求地址403(服务器端拒绝请求访问),双击请求内容在新的窗口页面打开用网址直接请求会发现请求成功。

解决办法

利用springCloud的gateway组件可以解决跨域问题

配置文件

spring:
  application:
    name: 服务名称
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]': # 匹配所有请求
            allowedOrigins: "*" #跨域处理 允许所有的域
            allowedMethods: # 支持的方法
              - GET
              - POST
              - PUT
              - DELETE
//一定要注意yml文件中的缩进问题  如果缩进的格式不对不能生效

启动类:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient  //使用注释开启注册中心
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class);
    }
}

解决结果

亲测可以解决跨域问题实现数据的请求