当我直接点击我的注册网址到服务控制器时,它运行良好并保存用户并给出 200 响应,但是当我通过网关点击同样的内容时,我的用户被保存,但花费了大量时间+显示此错误+我的回复是200:
错误:
signup:1 从源“http://localhost:4200”获取“http://localhost:8080/auth/register”的访问已被 CORS 策略阻止:“Access-Control-Allow-Origin”标头包含多个值 'http://localhost:4200, *',但只允许使用一个。让服务器发送带有有效值的标头,或者,如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
请求网址:
http://localhost:8080/auth/register
索取方式:
发帖
状态代码:
200 可以
推荐人政策:
跨源时严格源
我的网关后端代码是:
yml 文件:
cloud:
discovery:
enabled: true
gateway:
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "http://localhost:4200" # Allows requests from any origin
allowedMethods: "GET,POST" # Allows all HTTP methods (GET, POST, etc.)
allowedHeaders: "*" # Allows all headers
@Override
public GatewayFilter apply(Object config) {
return ((exchange, chain) -> {
if(validator.isSecured.test(exchange.getRequest()))
{
if(!exchange.getRequest().getHeaders().containsKey(HttpHeaders.AUTHORIZATION)){
throw new TokenMissingException("Token is not present");
}
String authHeader= exchange.getRequest().getHeaders().get(HttpHeaders.AUTHORIZATION).get(0);
if(authHeader!=null && authHeader.startsWith("Bearer ")) {
authHeader=authHeader.substring(7);
}
try {
jwtValidation.validateToken(authHeader);
}
catch (Exception ex){
throw new TokenMissingException("Not authorized to access the request");
}
}
return chain.filter(exchange);
});
}
}
我的前端代码是:
export class SignupComponent implements OnInit{
user : User = new User();
constructor(private signupService: SignupService){}
ngOnInit(): void {}
registerUser(){
console.log('User to register:', this.user);
this.signupService.registerUser(this.user).subscribe(
data => { console.log("User registered Successfully",data);
alert("User is registered")
},
error => {
console.error('Error registering user:', error);
alert("User not registered")
}
)
}
const BASE_URL="http://localhost:8080/auth";
@Injectable({
providedIn: 'root'
})
export class SignupService {
constructor(private http : HttpClient) { }
registerUser(user: User): Observable<Object>{
return this.http.post(BASE_URL+"/register",user);
}
}
将以下内容添加到 Spring Gateway 中的
application.yml
spring:
cloud:
gateway:
default-filters:
- DedupeResponseHeader=Access-Control-Allow-Origin, RETAIN_UNIQUE
这会删除导致问题的重复标头