我有一个WCF API,我必须连接到它。我没有真正访问它的代码,但这很有效:
$user = "login";
$password = "pwdstr";
$service_credentials = "external_api_user:sometext";
$arg = $user.'|'.sha1($user."somestr".$password);
$url='https://mysteryUrl.svc/projectsapi/' . $arg;
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_HTTPHEADER => array("Authorization: " . base64_encode("Basic " + service_credentials))));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
echo $resp;
我希望我的网页能从同一个api获取数据。到目前为止,我已经做到了这一点:
function requestFromApi() {
var user = "login";
var password = "pwdstr";
var service_credentials = "external_api_user:sometext";
var arg = user + '|' + sha1(user + "somestr" + password);
var url = 'https://mysteryUrl.svc/projectsapi/' + arg;
$.ajax({
url: url,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", base64_encode("Basic " + service_credentials));
xhr.setRequestHeader("User-Agent",'Codular Sample cURL Request');
},
type: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
alert(JSON.stringify(data));
},
error: function(){
alert("Cannot get data");
}
});
};
这当然是行不通的。我对网络开发完全陌生,所以任何帮助都将不胜感激。
Chrome控制台在加载页面时抛出这个:
Refused to set unsafe header "User-Agent"
XMLHttpRequest cannot load http s://verylongUrlAsInTheCodeAbove. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 400.
如何设置标题?在我看来,至少有一个问题是试图访问不同的域,那么我该怎么做呢?
是否有其他方法可以使用JavaScript访问此API?制作一个愚蠢的PHP"API",基本上只需重新发送我的数据就可以了吗?我对提议持开放态度。提前感谢!
编辑:我使用了JSONP:
<head>
<script type="text/javascript" src="js/jquery-2.1.1.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.4.5/jquery.mobile-1.4.5.js"></script>
<script type="text/javascript" src="js/functions.js"></script>
<script>
alert('1');
$(document).ready(function requestFromApi() {
var user = "login";
var password = "pwdstr";
var service_credentials = "external_api_user:sometext";
var arg = user + '|' + sha1(user + "somestr" + password);
var url='https://mysteryUrl.svc/projectsapi/' + arg;
$.ajax({
url: url+"?callback=?",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", base64_encode("Basic " + service_credentials) );
xhr.setRequestHeader("User-Agent",'Codular Sample cURL Request');
},
type: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function (dataWeGotViaJsonp) {
alert(dataWeGotViaJsonp);
},
error: function(){
alert("Cannot get data");
}
});
});
alert('2');
</script>
</head>
现在我收到Bad请求错误。那么错误可能在哪里呢?
您正处于良好的路径上,您遇到的错误是因为您的WPF服务器没有启用CORS标头,CORS标头会告诉Web浏览器哪些域可以连接到服务器,如果当前域不允许,浏览器会拒绝连接。
有关如何在WPF上启用CORS的示例:http://enable-cors.org/server_wcf.html.