How to enable CORS handler in light-4j service

503 views Asked by At

Question regarding CORS:

I used light-codegen with a swagger api. Now I want to enable CORS on my microservice.

To accomplish this, I did the following:

  1. added a cors.yml in the config folder (same location as swagger.json, service.yml, server.yml ...)
  2. added dependency to pom.xml: groupId: com.networknt artifactId: cors
  3. added the following line to service.yml, right under swaggerHandler: - com.networknt.cors.CorsHttpHandler

but the server does not add any cors header to the response. What did I do wrong?

2

There are 2 answers

1
Steve Hu On

It looks like you are following an older version of the tutorial and trying to upgrade to the latest version of light-4j framework. The configuration files have been changed a lot and that might contribute the complexity.

I have upgraded and published CORS tutorial and there a link to the working version on github. Let me know if you encounter any issue. Thanks.

https://doc.networknt.com/tutorial/cors/

2
Nagappan On

Finally I got the answer, we need to add PathHandlerProvider file in com.networknt.cors package. Need to remove the handlers.yml file from config folder. Just double check whether the service.yml file is same as in the git hub repo project.

This actually handles pre-flight request(OPTIONS) for cross origin requests with possible methods for CORS.

curl -k -H "Origin: http://test123.com" -H "Access-Control-Request-Method: POST"  -H "Access-Control-Request-Headers: X-Requested-With"  -X OPTIONS --verbose https://localhost:8443/v1/postData

Response was coming with following headers:

< access-control-allow-headers: X-Requested-With
< server: L
< access-control-allow-credentials: true
< content-length: 0
< access-control-allow-methods: GET
< access-control-allow-methods: POST