0

I have run in to a problem. Please help with your expertise.

I am developing web solution for a company. They have provided me Web API Method (REST). This API is in their domain. I am too access this from my domain. Even client has also already whitelisted my domain.

I am trying to call this method using below. But no luck. I am getting this below error.

Error NS_ERROR_DOM_BAD_URI: Access to restricted URI denied

function GetCustomerInfo() { var Url = "http://webapi.company.com/vx.x/customer/get?format=xml&mobile=9876543210" ; myXmlHttp = new XMLHttpRequest(); myXmlHttp.withCredentials = true; myXmlHttp.onreadystatechange = ProcessRequest; myXmlHttp.open( "GET", Url, true,"UID","PWD"); myXmlHttp.send(); }

function ProcessRequest() {

if(this.readyState == this.DONE) 
{
        if(this.status == 200 && this.responseXML != null ) 
    {
        alert ("Received Resoponse from Server");
        }
    else
    {
        alert ("Some Problem");
    }
    }

}

I am able to access this method from RESTClient in firefox plugin. Even I am able to access this method copying credentials in URL as below in browser address bar. I get anticipated response XML

http://UID:PWD@webapi.company.com/vx.x/customer/get?format=xml&mobile=9876543210

Please enlighten me where I am wrong. Perhaps JSONP can come to my help. But why i am not able to access this API using XMLHttpRequest.

Regards Rajul

4

1 回答 1

0

浏览器的同源策略不允许您将 XMLHttpRequests 发送到不同的域。您可以通过 firefox 插件或地址栏访问它的原因是那里没有应用同源策略。

你是对的,JSONP 可以解决你的问题,虽然你可能会遇到麻烦,因为你不控制服务器端。

回复您的评论:为了有效地使用 JSONP,服务器不仅需要以 JSON 格式返回您需要的数据,还需要在请求完成时调用回调的 javascript 代码。如果您不控制返回的数据,则无法为此添加必要的代码。维基百科文章为一般情况提供了一个很好的例子。

我从未使用过 CORS,因此无法为您提供太多信息。这似乎是一个更好的解决方案,但我想它在浏览器之间的兼容性并不令人难以置信。此外,据我了解,您还需要控制服务器,因为它似乎需要额外的 HTTP 标头。

于 2013-05-17T10:39:46.640 回答