I am currently troubleshooting my code to interact with a REST API.
My platform of choice is "EspoCRM" and I aim to utilize its API functionalities.
The official documentation recommends using Basic Authentication in this format:
"Authorization: Basic " + base64Encode(username + ':' + password)
Attempting to follow this guideline, I implemented the following snippet:
<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>
Upon running this code, I encountered an error in the console:
Uncaught SyntaxError: Unexpected token :
Although clicking on the error link displayed all the JSON data, the presence of this error hindered further data processing attempts.
If I switch from dataType: 'jsonp'
to dataType: 'json'
An alternate error surfaces:
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.
In an effort to rectify this issue, I added the following lines to my .htaccess file:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin: *
</IfModule>
The JSON output retrieved is as follows:
{"user":{"id":"1","name":"Admin","deleted":false,"isAdmin":true,"userName":"admin","password":"xNa3PPcGYcIGQJE4gZi4gnEJ1tv9XF1m7F490qTg.yLPG3Y3QtwRWQq.4RicYIro8akEOZXiWnXzuKg4P4Jnx1" ...