跨域问题CORS

不同端口,不同域名,浏览器向前端请求,前端服务响应后,浏览器再向后端服务发送ajax发送请求,使用代理解决问题。

第一种:

在vue.config.js文件里面配置请求后端接口:

javascript 复制代码
const {defineConfig} = require('@vue/cli-service')
module.exports = defineConfig({
    transpileDependencies: true,
    devServer: {
        proxy: {
            '/member': {
                target: 'http://localhost:1000',
                changeOrigin: true
            }
            ,
            '/business': {
                target: 'http://localhost:2000',
                changeOrigin: true
            },
            '/batch': {
                target: 'http://localhost:3000',
                changeOrigin: true
            }
        }
    }
})

相当于配置了代理,当请求头以/member开头的就会发送请求到端口1000的后端服务,例如

javascript 复制代码
 const onDelete = (record) => {
      axios.delete("/member/passenger/delete/" + record.id).then((response) => {
        const data = response.data;
        if (data.success) {
          notification.success({description: "删除成功!"});
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize,
          });
        } else {
          notification.error({description: data.message});
        }
      });
    };

配置

这两个方法都来自于WebMvcConfigurer接口

1.addCorsMappings解决的是跨域问题,执行位置:在请求进入 Controller 之前,由 Spring 的 CorsFilter 处理。

2.addInterceptors解决的是权限问题,执行位置:在请求进入 Controller 之前(preHandle)和之后(postHandle)。处理之前和之后的问题。

java 复制代码
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {
    @Resource
    LogInterceptor logInterceptor;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                //允许哪些源
                .allowedOriginPatterns("http://localhost:*", "http://127.0.0.1:*")
                //允许哪些方法
                .allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")
                .allowedHeaders("*")
                 //是否携带cookie
                .allowCredentials(true)
                .maxAge(3600);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(logInterceptor)
                 //排除哪些路径
                .addPathPatterns("/**");

    }
}
java 复制代码
@RestController
@RequestMapping("/passenger")
public class PassengerController {

    @DeleteMapping("/delete/{id}")
    public Result<Object> delete(@PathVariable Long id) {
        passengerService.delete(id);
        return new Result<>();
    }
}

就会请求到这个controller层里的根据id删除乘客这个接口,其他controller层同样可以,只要请求开头配对就可以。

第二种:

配置环境变量方法请求后端,在前端项目根目录下创建 .env文件并写入以下语句:

同时配置网关层,向其他后端接口发送请求,当前VUE_APP_SERVER就是网关层的后端接口地址,再由网关向其他后端接口发送请求。

网关模块的application.properties文件配置其他模块的接口:

html 复制代码
server.port=5000
# ===== 路由配置 =====
# member 模块
spring.cloud.gateway.server.webflux.routes[0].id=member
spring.cloud.gateway.server.webflux.routes[0].uri=lb://member
spring.cloud.gateway.server.webflux.routes[0].predicates[0]=Path=/member/**

# business 模块
spring.cloud.gateway.server.webflux.routes[1].id=business
spring.cloud.gateway.server.webflux.routes[1].uri=lb://business
spring.cloud.gateway.server.webflux.routes[1].predicates[0]=Path=/business/**

# batch 模块
spring.cloud.gateway.server.webflux.routes[2].id=batch
spring.cloud.gateway.server.webflux.routes[2].uri=lb://batch
spring.cloud.gateway.server.webflux.routes[2].predicates[0]=Path=/batch/**

# ===== 全局 CORS 配置 =====
spring.cloud.gateway.server.webflux.globalcors.cors-configurations.[/**].allowed-origin-patterns=http://localhost:*,http://127.0.0.1:*
spring.cloud.gateway.server.webflux.globalcors.cors-configurations.[/**].allowed-headers=*
spring.cloud.gateway.server.webflux.globalcors.cors-configurations.[/**].allowed-methods=*
spring.cloud.gateway.server.webflux.globalcors.cors-configurations.[/**].allow-credentials=true
spring.cloud.gateway.server.webflux.globalcors.cors-configurations.[/**].max-age=3600

配置nacos,通过nacos服务中心发现gateway:

html 复制代码
spring.application.name=gateway
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
spring.cloud.nacos.discovery.namespace=train
相关推荐
txxzjmzlh4 小时前
Alibaba Seata
spring cloud
方便面不加香菜3 天前
Docker Compose 文件 -- docker-compose.yml
spring cloud·docker·容器
真上帝的左手4 天前
31. 占位-14
分布式·spring cloud·架构·系统架构
captain3765 天前
SpringCloud(12)-Gateway
spring boot·spring cloud·gateway
行百里er6 天前
【Spring Insight 技术分享】如何让 AI 解释失败也不拖垮控制台
后端·spring cloud·开源
行百里er7 天前
【Spring Insight 技术分享】如何给 AI 接口调用做滑动窗口限流
spring boot·后端·spring cloud
逃逸线LOF12 天前
SpringCloud Stream
后端·spring·spring cloud
wz975415 天前
Docker 从 systemd 托管容器、overlay2 存储驱动到 Compose 多容器实战
spring cloud·docker·eureka
小郎君65820 天前
注解式脱敏:用 Jackson 的 ContextualSerializer 做字段级策略(一)
spring boot·spring cloud
jktantan20 天前
注解式脱敏:用 Jackson 的 ContextualSerializer 做字段级策略(一)
spring boot·后端·算法·spring cloud·系统架构