【发布时间】:2021-06-23 10:53:17
【问题描述】:
我正在使用Express Gateway 代理我的微服务。我正在使用Axios 从我的react 应用程序访问网关。但是,呼叫受到CORS Policy 的限制。我已经在快速网关和我的身份验证服务中启用了 CORS。我按照官方文档从link 为 Express Gateway 启用 CORS,从link 为身份验证服务(Express App)启用 CORS。这是我的代码。
Express Gateway config.yml
policies:
- log
- proxy
- jwt
- rate-limit
- request-transformer
- cors
pipelines:
authPipeline:
apiEndpoints:
- auth
policies:
-
cors:
-
action:
origin: '*'
methods: 'HEAD,PUT,PATCH,POST,DELETE'
allowedHeaders: ['Content-Type', 'Authorization']
-
log:
action:
message: 'auth ${req.method}'
-
proxy:
action:
serviceEndpoint: di
身份验证服务 app.js
const cors = require('cors');
// Enabling CORS
const corsOptions = {
origin: '*',
methods: ['POST', 'GET', 'PATCH', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization']
}
app.use(cors(corsOptions));
当我尝试使用 Insomnia(像 Postman 这样的客户端)时,我从服务器返回的标头如下图所示。
我在浏览器控制台中收到此错误。
Access to XMLHttpRequest at 'http://127.0.0.1:8080/api/v1/users/login' from
origin 'http://localhost:3000' has been blocked by CORS policy: Response to
preflight request doesnt pass access control check: No 'Access-Control-
Allow-Origin' header is present on the requested resource.
我不确定我错过了什么。如果您需要其他任何东西,请告诉我,我会尽快提供。每一次试图解释我的案例有什么问题的尝试都非常感谢。
编辑:添加 API 调用 sn-p
const config = {
headers: {
'Content-Type': 'application/json',
},
};
const body = JSON.stringify({ email, password });
const res = await axios.post('http://127.0.0.1:8080/api/v1/users/login', body, config);
【问题讨论】:
-
为什么要使用origin:'*'?
-
好吧,我只是想让它不管来源如何都能正常工作。这就是我使用它的原因。 @JamesMcLeod
-
但是你不知道先验的可能起源的集合吗?这似乎违背了 CORS 的目的。你能用一个特定的值试试看它是否有效吗?
-
@JamesMcLeod 我只保留了我的反应服务器的端口后尝试过。我仍然得到同样的错误。
标签: node.js reactjs cors microservices express-gateway