Access to XMLHttpRequest at '…' from origin 'http://localhost' has been blocked by CORS policy [duplicate]

爱⌒轻易说出口 提交于 2021-01-27 07:06:48

问题



I'm trying to demo an api call with javascript to get Json result. Here is what I did:

<!DOCTYPE html>
<html>
    <head>
    </head>
        <script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
    <body>
        <div class="render-form">
            <script>
                $(document).ready(function() {
                    $.ajax({
                        type: 'GET',
                        headers:{    
                            'Accept': 'application/json',
                            'Content-Type': 'application/json',
                            'Access-Control-Allow-Origin': '*' 
                        },
                        url: 'http://127.0.0.1:8080/activiti-rest/service/form/form-data?taskId=21159',
                        dataType: 'json',
                        success: function (data) {
                            alert(JSON.stringify(data));
                        }
                    });
                })
            </script>
        </div>
    </body>
</html>

But when I run it, I got an error:

Access to XMLHttpRequest at 'http://127.0.0.1:8080/activiti-rest/service/form/form-data?taskId=21159' from origin 'http://localhost' 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.

After searching many post in here, I added:

headers:{    
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*' 
},

But it still not work with that error. How should I fix this?
Any reply would be very appreciate!
Thank you very much!  


回答1:


If you are running the Activiti framework on Tomcat, you can config CORS support in Tomcat via a filter. You need to add this filter to your web.xml file and configure it to match your requirements.

Check Tomcat's documentation:
http://tomcat.apache.org/tomcat-8.0-doc/config/filter.html#CORS_Filter

Also please note:

  • As @Quentin pointed out in a comment you are using a jQuery version that is 5 years old and dangerously out of date.
  • The Access-Control-Allow-Origin header you are using in your ajax request is a response header, not a request header, so it should be returned by the server in the response. You can't use response headers in a request.


来源:https://stackoverflow.com/questions/55627247/access-to-xmlhttprequest-at-from-origin-http-localhost-has-been-blocke

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