从浏览器(jQuery 脚本)访问 API 被阻止。这是我收到的错误消息:
从源“null”访问“http://localhost:8765/conversion/convert”的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:无“Access-Control-Allow-” Origin' 标头存在于请求的资源上。
HTML 文件中的我的 jQuery 脚本:
$.ajax({
type: 'POST',
url: 'http://localhost:8765/conversion/convert',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer MY_JWT_TOKEN'
},
data: JSON.stringify({
id: 1,
from: 'usd',
to: 'bdt',
quantity: 100
}),
success: function(data) {
console.log(data);
},
error: function(error) {
console.error(error);
}
});
Maven 依赖项和版本:
我已经使用 API 网关配置了 OAuth2 (Keycloak),并按照官方 Spring Cloud 页面上的指示在我的网关服务配置文件 (yml) 中使用了 CORS (globalcors) 配置。我也尝试了互联网上的所有不同方法,似乎没有任何效果。
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-ui: http://localhost:9000/realms/Microservices-demo-realm
jws-algorithm: RS256
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "*"
allowedMethods: "*"
allowedHeaders: "*"
default-filters:
- DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin RETAIN_UNIQUE
- name: TokenRelay
routes:
- id: conversion-service
uri: lb://currency-conversion
predicates:
- Path=/conversion/**
这是 Google Chrome 网络控制台:
我也尝试过一个小型的 ReactJS 应用程序,CORS 也被阻止了。这是截图:
请帮忙!
无需进行 CORS 配置即可避免 CORS 错误的一个简单方法是具有相同的来源(也通过网关为您的网站提供服务,而不仅仅是 API)。
另外,这不是问题,但将网关配置为资源服务器是一个坏主意,特别是当它被浏览器中运行的某些 Javascript 代码查询时。
最好将其配置为具有
oauth2Login()
和 TokenRelay=
过滤器的客户端。网关后面的 REST API 将成为 oauth2ResourceServer()
配置的候选者。