网关配置快速入门

前端请求统一发送到网关:

window.SITE_CONFIG['baseUrl'] = 'http://localhost:8088/api';

网关服务中配置路由转发:

server:

port: 8088

spring:

application:

name: gulimall-gateway #服务名称

config:

import: nacos:bootstrap.yaml #引入bootstrap.yaml依赖

cloud:

nacos:

discovery:

server-addr: 127.0.0.1:8848 #nacos地址

gateway:

routes:

- id: product_route

uri: lb://gulimall-product

predicates:

- Path=/api/product/**

filters:

- RewritePath=/api/(?.*), /$\{segment}

# 后台管理前端请求

- id: admin_route

uri: lb://renren-fast

predicates:

- Path=/api/**

# 前端项目发的请求都带上前缀,/api,以后网关遇到/api开头的请求都先发给renren-fast处理

# 上面这种写法会导致请求验证码的路径变为:http://localhost:8088/api/captcha.jpg

# 正确的请求地址应该是:http://localhost:8088/renren-fast/captcha.jpg

filters:

- RewritePath=/api/(?.*), /renren-fast/$\{segment}

# 利用RewritePath,将前缀/api替换成/renren-fast

# 所以前端发出的请求为:http://localhost:8088/api/...

# 网管收到并处理后,转发到后台的请求为:http://localhost:8088/renren-fast/...

网关服务中新建配置类GulimallCorsConfiguration处理跨域问题:

package com.atguigu.gulimall.gateway.config;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.cors.CorsConfiguration;

import org.springframework.web.cors.reactive.CorsWebFilter;

import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**

* @title: GulimallCorsConfiguration

* @Author DengMj

* @Date: 2024/1/21 15:36

* @Version 1.0

*/

@Configuration

public class GulimallCorsConfiguration {

@Bean

public CorsWebFilter corsWebFilter(){

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

CorsConfiguration corsConfiguration = new CorsConfiguration();

//1. 配置跨域

corsConfiguration.addAllowedHeader("*");

corsConfiguration.addAllowedMethod("*");

corsConfiguration.addAllowedOriginPattern("*");

corsConfiguration.setAllowCredentials(true);

source.registerCorsConfiguration("/**", corsConfiguration);

return new CorsWebFilter(source);

}

}

推荐阅读

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。