先直接在后端加上@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);
}
}