简体   繁体   中英

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

I am using "EspoCRM" and now i want to start working with the 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. 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'

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

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

the json output is:

{"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. 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.

The data you get from AJAX callback is JSON itself. You cannot parse JSON data as parse returns JSON data itself. So following code is unnecessary

JSON.parse(data);

Just assign

var json = data;

Or use data directly. This will solve your first error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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