【问题标题】:Sending Ajax request with Basic Authentication and Raw data使用基本身份验证和原始数据发送 Ajax 请求
【发布时间】:2014-08-04 01:30:39
【问题描述】:

我正在像这样进行 ajax 调用:

            var username = "someusername";
            var password= "somepassword";

    var datam = '{"description":"my description","account":"mehame","username":"hakan","password":"11"}';

    $.ajax
            ({
                url: "http://mywebsite.com:8080/directory/send",
                contentType: "application/json",
                data: datam,
                dataType: 'text',
                type: "PUT",
                headers: {
                    "Authorization": btoa(username + ":" + password)
                  },
                beforeSend: function (){
                    //xhr.setRequestHeader('Authorization', make_base_auth(username, password));
                    console.log(datam);
                },
                success: function (){
                    alert("Here's lots of data, just a string: " + datam);
                },
                error : function(){
                    alert("Here's lots of data, just a string: " + datam);
                }
            });

        });

萤火虫控制台给了我“跨域错误”(并返回错误):

跨域请求被阻止:同源策略不允许读取位于http://mywebsite.com:8080/directory/send 的远程资源。这可以通过将资源移动到同一个域或启用 CORS 来解决。” p>

但在我的 chrome 扩展名中,名称是“PostMan”,它完全可以工作。

有什么不同?

【问题讨论】:

  • 你在后端使用哪种编程语言?>
  • 我在后端使用java
  • 然后在后端的java文件中,检查有效数据(Usernm+pwd),如果正确,则返回True响应ajax,否则返回False。很简单
  • 这是真的。处理 chrome 扩展。但是在html页面中不起作用。
  • 你使用 JSP 正确吗?请说明为什么它不起作用。

标签: jquery ajax rest


【解决方案1】:

由于同源策略,您不能对外部主机名或端口号执行 ajax 请求。 http://en.wikipedia.org/wiki/Same-origin_policy

您必须在 http 标头中启用 CORS:http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

您也可以查看此帖子以了解如何操作:cant get CORS working in chrome and firefox

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    相关资源
    最近更新 更多