在快速网关中请求的资源上没有返回Access-Control-Allow-Origin头的CORS策略

问题描述 投票:0回答:1

我正在使用Express Gateway作为与后端服务器连接的API网关。我的前端在localhost:3000上运行,而Express网关在localhost:8080上运行。当我尝试从前端访问后端时,在浏览器中出现cors错误。但是,使用邮递员时一切正常。

我的gateway.config.yml(仅一个管道)

user:
    apiEndpoints:
      - user
    policies:
      - cors:
        - action:
            origin: "*"
            credentials: true
            methods: ['GET','POST','PUT','DELETE']
            allowedHeaders: ['Content-type','Authorization','Origin','Access-Control-Allow-Origin','Origin', 'Accept', 'X-Requested-With', 'Content-Type', 'Access-Control-Request-Method', 'Access-Control-Request-Headers','Authorization', 'Access-Control-Allow-Origin','X-TEST']
            exposedHeaders : ['Content-type','Authorization','Origin','Access-Control-Allow-Origin','Origin', 'Accept', 'X-Requested-With', 'Content-Type', 'Access-Control-Request-Method', 'Access-Control-Request-Headers','Authorization', 'Access-Control-Allow-Origin','X-TEST']
            preflightContinue: true
      - jwt:
        - action:
            secretOrPublicKey: 'secret'
            checkCredentialExistence: false
      - request-transformer:
        - action:
            body:
              add:
                user: req.user
      - proxy:
        - action:
            serviceEndpoint: noAuthService

我收到以下错误。

Access to XMLHttpRequest at 'http://localhost:8080/api/user/31a19f8a-c76d-4051-a944-dad1b676c550' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

任何想法如何解决此问题???

node.js cors cross-domain api-gateway express-gateway
1个回答
0
投票
我的第一个问题是,为什么不将网关代码合并到前端服务器中?为什么需要两个单独的服务器?

然后,要处理飞行前请求,您需要处理OPTIONS请求(而不是GET或POST,传入的HTTP动词是OPTIONS),如图here所示。您可以阅读有关预检请求here的信息,并查看一些如何处理它们的示例。在Express中,您可以使用

[如果使用cors()程序包,则可以看到一些飞行前处理示例herehere

© www.soinside.com 2019 - 2024. All rights reserved.