網頁

2021年2月25日 星期四

解決 跨網站 webapi 出現 blocked by CORS policy

因為跨網站使用 webapi 出現
Access to XMLHttpRequest at 'https://webapi.url' from origin 'https://web.url' 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.

因為使用 nginx 轉到 tomcat
不用修改 /etc/nginx/sites-available/config
要修改 tomcat 的 WEB-INF/web.xml 在 <web-app> 內加上如下內容
        <filter>
                <filter-name>CorsFilter</filter-name>
                <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
                <init-param>
                        <param-name>cors.allowed.origins</param-name>
                        <param-value>https://www.yoursite:8443,http://yoursite2.com</param-value>
                </init-param>
                <init-param>
                        <param-name>cors.allowed.methods</param-name>
                        <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
                </init-param>
                <init-param>
                        <param-name>cors.allowed.headers</param-name>
                        <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
                </init-param>
                <init-param>
                        <param-name>cors.exposed.headers</param-name>
                        <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
                </init-param>
                <init-param>
                        <param-name>cors.support.credentials</param-name>
                        <param-value>true</param-value>
                </init-param>
                <init-param>
                        <param-name>cors.preflight.maxage</param-name>
                        <param-value>10</param-value>
                </init-param>
        </filter>
        <filter-mapping>
                <filter-name>CorsFilter</filter-name>
                <url-pattern>/*</url-pattern>
        </filter-mapping>