首页 > 解决方案 > 从前端应用程序调用时,Express Gateway(启用密钥身份验证)给出 COR 问题

问题描述

描述问题

我分别使用 Angular 和 nginx 开发和部署了我的前端应用程序。

资源服务器是使用无压力 NodeJS 开发的。

流量是

UI -> express gateway -> resource server

每当尝试从 UI 调用 API 时,在 express 网关中启用了 key-auth ,都会出错

从源“ http://url ”访问“ http://ip:port/api/function_name ”处的 XMLHttpRequest已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头.

Same API when called from Postman works though. It also works if I remove 'key-auth' from gateway. 

共享在各个级别完成的代码更改:

代码 -快速网关

example:
    apiEndpoints:
      - example
    policies:
      - cors:
          - action:
              origin: ["*"]
              methods: "HEAD,GET,PUT,PATCH,POST,DELETE,OPTIONS"
              preflightContinue: true
              optionsSuccessStatus: 204
              maxAge: 600
              allowedHeaders:
                [
                  "Origin, X-Requested-With, Content-Type, Accept, Authorization",
                ]
      - key-auth:
          - condition:
              name: not
              condition:
                  name: method
                  methods:
                    - OPTIONS
      - proxy:
          - action:
              serviceEndpoint: exampleService
              proxyTimeout: 0

代码 -

const httpOptions = {
    headers: new HttpHeaders({
        'Content-Type': 'Application/json; charset=UTF-8',
        'Authorization': "Bearer " + apiKey,
        'Access-Control-Allow-Origin': '*'
    }),
};

代码 -资源服务器 - routes.js

export default function routes(app) {
   app.use(cors());
   // Also tried setting res.setHeader explicitly, but no success.
}

代码——nginx级别

server(){
   ...
   location / {
        # Simple Requests
        if ($request_method ~* "(GET|POST)") {
             add_header "Access-Control-Allow-Origin"  *;
        }

        # Preflighted requests
        if ($request_method = OPTIONS ) {
             add_header "Access-Control-Allow-Origin"  *;
             add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
             add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
             return 200;
        }

        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
   }
}

我已经浏览了有关此问题的各种链接,尝试了如上所示的多种方法,但找不到任何解决方案,因此提出了新的解决方案。

如何删除此 COR 错误?

标签: node.jsnginxcorsexpress-gateway

解决方案


在进行以下更正/更改后,我已经解决了这个问题:

代码 - Angular (用 apiKey 替换承载)

const httpOptions = {
    headers: new HttpHeaders({
        'Content-Type': 'Application/json; charset=UTF-8',
        'Authorization': "apiKey " + apiKey,
        'Access-Control-Allow-Origin': '*'
    }),
};

代码 - nginx 级别 (修改 location 函数中的条件)

server {
        ....
        location / {
            if ($request_method = OPTIONS) {
                return 204;
            }
            add_header Access-Control-Allow-Origin *;
            add_header Access-Control-Max-Age 3600;
            add_header Access-Control-Expose-Headers Content-Length;
            add_header Access-Control-Allow-Headers Range;
            try_files $uri $uri/ =404;
        }
}

其他一切都保持不变。


推荐阅读