前后端跨域问题

先直接在后端加上@CrossOrigin看行不行,加了之后发现莫名奇妙微服务访问得了,网关却无法访问,但postman测试通过,所以觉得还是跨域的问题,最后再配置前端的跨域配置,这里使用的是vue3,再vue.config.js中加入了proxy的配置

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer:{
    proxy: {
      '/api': {
        target: 'http://localhost:50000', // 目标服务器地址
        changeOrigin: true, // 是否改变源地址
        pathRewrite: {
          '^/api': '' // 重写路径
        }
      }
    }
  }
})

第一个/api指匹配所有以/api开头的请求,第二个^/api,也就是属性的字面意思,正则表达式将/api选出来并替换为另一个地址,这里写的空字符串,结果就是删掉了/api,在请求时,写的/api/user/login,实际上请求的地址是

http://localhost:50000/user/login

更正

网关访问不了是因为使用了spring could gateway,先被网关的跨域问题拦截了

解决方法只需要在config中加跨域处理的配置类即可,因为是个人项目不上线,这里全部放行

package org.nowiam.user.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;

@Configuration
public class GlobalCorsConfig {

    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // 这里仅为了说明问题,配置为放行所有域名,生产环境请对此进行修改
        config.addAllowedOrigin("*");
        // 放行的请求头
        config.addAllowedHeader("*");
        // 放行的请求方式,主要有:GET, POST, PUT, DELETE, OPTIONS
        config.addAllowedMethod("*");
        // 暴露头部信息
        config.addExposedHeader("*");
        // 是否发送cookie
        config.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值