我想了解我的代码与rest api一起使用的问题
我正在使用" EspoCRM"现在我想开始使用api。
在他们要求使用的documentation中:使用基本身份验证,如:
"Authorization: Basic " + base64Encode(username + ':' + password)
所以我尝试使用这段代码:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" >
var creds = {
username: "myuser",
password: "mypass"
};
var credentials = btoa(creds.username + ":" + creds.password);
$.ajaxSetup({
xhrFields: { withCredentials: false },
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic" + credentials);
return true;
}
});
$.ajax({
url: 'http://crmurl.com/api/v1/App/user',
type: 'GET',
dataType: 'jsonp',
async: false,
success: function (data) {
console.log(data);
var json = JSON.parse(data);
alert(json.user.userName);
}
});
</script>
使用此代码后,我在控制台中收到错误:
Uncaught SyntaxError: Unexpected token :
当我点击错误链接时,我可以看到所有的json数据。但由于错误,我无法处理数据。无论我尝试什么。
如果我从dataType: 'jsonp'
更改为dataType: 'json'
我收到此错误:
XMLHttpRequest cannot load http://crmurl.com/api/v1/App/user. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.domain.com' is therefore not allowed access. The response had HTTP status code 401.
我添加了htaccess
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin: *
</IfModule>
json输出是:
{"user":{"id":"1","name":"Admin","deleted":false,"isAdmin":true,"userName":"admin","password":"xNa3PPcGYcIGQJE4gZi4gnEJ1tv9XF1m7F490qTg.yLPG3Y3QtwRWQq.4RicYIro8akEOZXiWnXzuKg4P4Jnx1","salutationName":"","firstName":"","lastName":"Admin","isActive":true,"title":"","emailAddress":"demo@espocrm.com","phoneNumber":"+44(203)695-03-80","createdAt":"2015-07-11 05:03:05","defaultTeamId":null,"defaultTeamName":null,"teamsIds":[],"teamsNames":{},"avatarName":null,"avatarId":null},"acl":{"table":{"Email":{"read":"all","edit":"all","delete":"no"},"EmailAccountScope":true,"EmailTemplate":{"read":"all","edit":"all","delete":"no"},"Account":{"read":"all","edit":"all","delete":"no"},"Calendar":true,"Call":{"read":"all","edit":"all","delete":"no"},"Campaign":{"read":"all","edit":"all","delete":"no"},"Case":{"read":"all","edit":"all","delete":"no"},"Contact":{"read":"all","edit":"all","delete":"no"},"Document":{"read":"all","edit":"all","delete":"no"},"DocumentFolder":{"read":"all","edit":"all","delete":"no"},"Lead":{"read":"all","edit":"all","delete":"no"},"Meeting":{"read":"all","edit":"all","delete":"no"},"Opportunity":{"read":"all","edit":"all","delete":"no"},"TargetList":{"read":"all","edit":"all","delete":"no"},"Task":{"read":"all","edit":"all","delete":"no"},"User":{"read":"all","edit":"no","delete":"no"},"Team":{"read":"all","edit":"no","delete":"no"},"Note":{"read":"all","edit":"own","delete":"own"},"EmailAddress":{"read":"no","edit":"no","delete":"no"},"PhoneNumber":{"read":"no","edit":"no","delete":"no"},"EmailAccount":{"read":"own","edit":"own","delete":"own"},"Role":false},"assignmentPermission":"all","userPermission":"no"},"preferences":{"id":"1","timeZone":"UTC","dateFormat":"MM\/DD\/YYYY","timeFormat":"HH:mm","weekStart":0,"thousandSeparator":",","decimalMark":".","defaultCurrency":"USD","dashboardLayout":[{"name":"My Espo","layout":[[{"name":"Stream","id":"d4"},{"name":"SalesByMonth","id":"d11"},{"name":"SalesPipeline","id":"d12"}],[{"name":"Tasks","id":"d3"},{"name":"OpportunitiesByLeadSource","id":"d14"},{"name":"OpportunitiesByStage","id":"d15"}]]}],"dashletOptions":null,"smtpServer":"","smtpPort":25,"smtpAuth":false,"smtpSecurity":"","language":"es_ES","exportDelimiter":";","receiveAssignmentEmailNotifications":true,"autoFollowEntityTypeList":[],"signature":"<br>","defaultReminders":[]},"token":null}
答案 0 :(得分:1)
当您使用JSON进行呼叫时,由于缺少CORS标头,您的访问将被拒绝。因此你得到错误
XMLHttpRequest cannot load http://crmurl.com/api/v1/App/user. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.domain.com' is therefore not allowed access. The response had HTTP status code 401.
这解释了第二个错误。现在,由于CORS不存在,JSONP只是获取数据的方法,它增加了CORS头。
从AJAX回调中获得的数据是JSON本身。您无法解析JSON数据,因为parse
会返回JSON数据本身。所以下面的代码是不必要的
JSON.parse(data);
只需分配
var json = data;
或直接使用data
。这将解决您的第一个错误。