简体   繁体   English

Ajax:其余api调用给出错误:未捕获的SyntaxError:意外的令牌:

[英]Ajax: rest api call give error: Uncaught SyntaxError: Unexpected token :

i am trying to understand what is the problem with my code to work with rest api 我试图了解我的代码与REST API一起工作的问题

I am using "EspoCRM" and now i want to start working with the api. 我正在使用“ EspoCRM”,现在我想开始使用api。

In the documentation they ask to use: uses Basic Authentication like: 他们在文档中要求使用:使用基本身份验证,例如:

"Authorization: Basic " + base64Encode(username + ':' + password)

So i try to use this code: 所以我尝试使用此代码:

<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>

After i use this code i get error in the console: 使用此代码后,我在控制台中得到错误:

Uncaught SyntaxError: Unexpected token :

When i click on the error link i can see all the json data. 当我单击错误链接时,我可以看到所有json数据。 but because of the error i can't work with the data. 但由于错误,我无法处理数据。 no matter what i try. 不管我尝试什么。

If i change from dataType: 'jsonp' to dataType: 'json' 如果我从dataType: 'jsonp'更改为dataType: 'json'

I get this error: 我收到此错误:

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.

I have add in htaccess 我在htaccess中添加了

<IfModule mod_headers.c>
  Header set Access-Control-Allow-Origin: *
</IfModule>

the json output is: 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}

When you make a call with JSON your access is denied as CORS headers is absent. 当您使用JSON进行调用时,由于缺少CORS标头,因此您的访问被拒绝。 Hence you get the error 因此,您会得到错误

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.

This explains the second error. 这解释了第二个错误。 Now, since CORS is not present, JSONP is only way to get the data, which adds CORS headers. 现在,由于不存在CORS,JSONP是获取数据的唯一方法,它会添加CORS标头。

The data you get from AJAX callback is JSON itself. 您从AJAX回调获取的数据是JSON本身。 You cannot parse JSON data as parse returns JSON data itself. 您无法解析JSON数据,因为parse返回JSON数据本身。 So following code is unnecessary 因此,以下代码是不必要的

JSON.parse(data);

Just assign 刚分配

var json = data;

Or use data directly. 或直接使用data This will solve your first error. 这将解决您的第一个错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM