Jhipster CORS enable

天涯浪子 提交于 2021-01-28 03:11:18

问题


I am using Jhipster to generate API.

My api is on lets call it :

https://api.staging.test.com/

and my FE app is on :

https://staging.test.com/

Here is my config for Cors enable in application-prod.yml

cors:
     allowed-origins: "https://staging.test.com/"
     allowed-methods: "*"
     allowed-headers: GET, PUT, POST, DELETE, OPTIONS
     exposed-headers: "Authorization,Link,X-Total-Count"
     allow-credentials: true
     max-age: 1800

I still get this error :

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://staging.test.com' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Is there anything more that needs to be done in Spring boot to enable CORS ?


回答1:


The only config needed to enable CORS in JHipster's Prod mode is to set the jhipster.cors configuration like below. One thing to note is that if your frontend is using a port, that needs to be included in the allowed-origins key.

jhipster:
    cors:
        allowed-origins: "https://staging.test.com:8080"
        allowed-methods: "*"
        allowed-headers: "*"
        exposed-headers: "Authorization,Link,X-Total-Count"
        allow-credentials: true
        max-age: 1800

This is loaded by JHipsterProperties and used in WebConfigurer.java to apply the CORS configuration.




回答2:


Faced the same issue. The easiest and safest way I found is to enable cors only for the specific methods you need exposed in your controller. At the method which serves your api, add @CrossOrigin("*") annotation. This works in production and there is no need to make any changes to application-prod.yml.



来源:https://stackoverflow.com/questions/51730409/jhipster-cors-enable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!