发布数据时的跨源错误 - ajax

时间:2018-05-03 12:29:31

标签: jquery ajax

我正在测试我的api如下:

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    </head>
    <body>


        <div onclick="sendData()">Send</div>

        <script>
            function sendData(){

                var sendInfo = {
                    "name" : "test"
                };

                $.ajax({
                    //headers: { 'Access-Control-Allow-Origin': '*' },
                    beforeSend: function(xhr) {
                        xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
                        xhr.setRequestHeader("Content-Type","application/json");
                        xhr.setRequestHeader("Accept","application/json");
                },
                url: "http://localhost:8080/someapi",
                data:  sendInfo,
                type: "POST",
                dataType: "json",
                success: function(data){
                    //do something after something is recieved from php
                },
                error: function(){
                    //bad request
                }
            });
        }

        </script>
    </body>
</html>

我收到以下错误:

  

无法加载http://localhost:8080/someapi:对预检请求的响应未通过访问控制检查:否&#39; Access-Control-Allow-Origin&#39;标头出现在请求的资源上。起源&#39; null&#39;因此不允许访问。响应的HTTP状态代码为403。

如何解决这个问题?

0 个答案:

没有答案