node.jsnginxcorsexpress-gateway

Express Gateway (key-auth enabled) giving CORs issue when called from front-end application


Issue with description

I have my front end application developed and deployed using Angular and nginx respectively.

Resource server is developed using No stress NodeJS.

Flow is

UI -> express gateway -> resource server

Whenever trying to call an API from UI, with key-auth enabled in express gateway, getting error

Access to XMLHttpRequest at 'http://ip:port/api/function_name' from origin 'http://url' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

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

Sharing the code changes done at various levels:

Code - Express 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

Code - Angular

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

Code - Resource Server - routes.js

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

Code - nginx level

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;
   }
}

I have gone through various links on this issue, tried multiple things as shown above but couldn't find any solution, thus raising new one.

How to remove this CORs error?


Solution

  • I have solved the issue after making below corrections/changes:

    Code - Angular (Replaced Bearer with apiKey)

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

    Code - nginx level (Modified the condition in location function)

    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;
            }
    }
    

    Everything else remains same.