I could not acquire the image from the API of spotify - javascript

I'm trying to create a site in which, through the Spotify Web API, I display the information of a certain element (Artist, Track, Album, etc ...). In the background of the object of the answer, however, I would like to set the image that is provided directly by Spotify but, after several attempts, I still can not.
This is my function.
function ricercaArtista(){
var xhr = new XMLHttpRequest();
var artist =document.getElementById("artista").value;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var result = '';
for(var i = 0; i < response.artists.items.length; i++){
console.log(response.artists.items[i]);
result +='<div class="panel panel-primary" style="background:url('+
response.artists.items[i].images[1].url+');"><div class="panel-body">' +
'name : ' + response.artists.items[i].name + '<br/>' +
'popularity : ' + response.artists.items[i].popularity + '<br/>' +
'type : ' + response.artists.items[i].type + '</div></div>';
}
alert
document.getElementById("artists").innerHTML = result;
}
};
xhr.open('GET', "https://api.spotify.com/v1/search?q="+artist+"&type=artist&market=IT&limit=10&offset=5", true);
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Bearer BQAnHZ_1kZFp_6rNx7jWXz-wfK9KTp2gTmuviXisgsJy8IAjnF_Hbo701Y5UMu7viFb0vaKG6wBAcLQMhfNUBjzGZpt1M3UaWGEKWDVmziEh-s6ECFNeVFCifdD3C38w3q_jGdnovDUlek2f463hnyPUlpoC4xb2uA');
xhr.send();
}
the error of the Console of Chrome is:
Index.html:29 Uncaught TypeError: Cannot read property 'url' of undefined at XMLHttpRequest.xhr.onreadystatechange

#Pointy is right, some the records has an empty array on Image path.
Look at the fetch below it returns different records to search Bob marley.
you can see the result in console.
in this case you need to check image path if it's empty Do something.
fetch("https://api.spotify.com/v1/search?q=bob marley&type=artist&market=IT&limit=10&offset=5")
.then(res=> res.json())
.then(data=> console.log(data.artists.items))
.catch(err=> console.log(err));

Related

eBay API CORS request using JavaScript returns undefined

I want to fetch JSON data from eBay Sandbox using JavaScript
I tried getting it through CORS request (as it is a cross domain request) but it returns undefined. I tried lots of different code but I haven't found any solutions.
What I want to do is that fetch the products from eBay and display them in my Chrome extension.
Any help is appreciated.
You can send a GET request to the URL.
const http = require('http');
let url = 'http://svcs.sandbox.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&SECURITY-APPNAME=NiraliAc-FlashSal-SBX-7d56b4536-d82a9262&GLOBAL-ID=EBAY-US&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=harry%20potter&paginationInput.entriesPerPage=3&itemFilter(0).name=MaxPrice&itemFilter(0).value=25&itemFilter(0).paramName=Currency&itemFilter(0).paramValue=USD&itemFilter(1).name=FreeShippingOnly&itemFilter(1).value=true&itemFilter(2).name=ListingType&itemFilter(2).value(0)=AuctionWithBIN&itemFilter(2).value(1)=FixedPrice&itemFilter(2).value(2)=StoreInventory';
http.get(url, res => {
let body = '';
res.on('data', data => body += data);
res.on('end', () => {
console.log(body);
});
});
I found a solution by making a CORS request and using the CORS Anywhere API from https://github.com/Rob--W/cors-anywhere/
var cors_api_url = 'https://cors-anywhere.herokuapp.com/';
function doCORSRequest(options, printResult) {
var x = new XMLHttpRequest();
x.open(options.method, cors_api_url + options.url);
x.onload = x.onerror = function() {
printResult(
options.method + ' ' + options.url + '\n' +
x.status + ' ' + x.statusText + '\n\n' +
(x.responseText || '')
);
};
x.send(options.data);
}
(function() {
var outputField = document.getElementById('output');
new1();
function new1() {
// e.preventDefault();
doCORSRequest({
method: 'GET',
url: url,
}, function printResult(result) {
//result contains the response
//write your code here
});
};
})();
Source: https://github.com/Rob--W/cors-anywhere/blob/master/demo.html
(Live example: https://robwu.nl/cors-anywhere.html)

Javascript serialized POST

I am trying to achieve that when I call the JS function, a post request is send. In my browser I would send:
http://myuser:password#hc2:80/api/callAction?deviceID=185&name=turnOn
This works. Yet in my code it doesn't.
Important to note:
- Chrome does raise an Error: Request doesn't pass access control. If I disable this in Chrome, I doesn't display this error (yet no response from the server either).
<script type="text/javascript">
function changestate() {
var http = new XMLHttpRequest();
http.withCredentials = true;
var user = "bassie"
var pass = "password"
var url = "http://hc2/api/callAction";
var params = "deviceID=185&name=turnOff";
http.open("POST", url, true);
http.setRequestHeader("Authorization", "Basic " + user + ":" + pass);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
alert(http.responseText);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
}
</script>
The equivalent to putting the URL in the browser's location is a GET request, not POST.
Since you're sending a cross-domain request, you won't be able to read the response (unless you relay through a proxy on your origin server). So you can't read http.responseText, and can simply omit the onreadystatechange function; you'll just have to assume it
function changestate() {
var http = new XMLHttpRequest();
http.withCredentials = true;
var user = "bassie"
var pass = "password"
var url = "http://hc2/api/callAction";
var params = "deviceID=185&name=turnOff";
http.open("GET", url + "?" + params, true);
http.setRequestHeader("Authorization", "Basic " + user + ":" + pass);
http.send();
}
Eventually ended up creating a sort of like proxy. This was the main component. Not in the example (My script gets the HTTP requested) and gets the output. Below the gist of it:
req = urllib.request.Request('http://hc2:80/api/callAction?param1=1&param2=2')
credentials = ('%s:%s' % ('user', 'password'))
encoded_credentials = base64.b64encode(credentials.encode('ascii'))
req.add_header('Authorization', 'Basic %s' %
encoded_credentials.decode("ascii"))
response = urllib.request.urlopen(req)

Accessing Sharepoint Project web app REST from separate app

I need to connect to our corporate PWA. This is the code I'm using:
// var endpointUrl = 'https://<companySite>.sharepoint.com/sites/pwa/_api/web/lists';
var endpointUrl = 'https://<companySite>.sharepoint.com/sites/pwa/_api/ProjectData/Projects?$select=ProjectName';
var xhr = new XMLHttpRequest();
xhr.open("GET", endpointUrl);
// The APIs require an OAuth access token in the Authorization header, formatted like this: 'Authorization: Bearer <token>'.
xhr.setRequestHeader("Authorization", "Bearer " + token);
xhr.setRequestHeader("Accept", "application/json");
$("#header").html("Requesting: " + endpointUrl);
// Process the response from the API.
xhr.onload = function () {
if (xhr.status == 200) {
var formattedResponse = JSON.stringify(JSON.parse(xhr.response), undefined, 2);
$("#results").html("<pre>" + formattedResponse + "</pre>");
} else {
$("#results").html("HTTP " + xhr.status + "<br>" + xhr.response);
}
}
// Make request.
xhr.send();
I've tried also a few different ways, all using Bearer token.
The problem is that this code works for accessing https://<companySite>.sharepoint.com/sites/pwa/_api/web/lists but doesn't for https://<companySite>.sharepoint.com/sites/pwa/_api/ProjectData/Projects?$select=ProjectName
For the latter it returns:
{"odata.error":{"code":"20010, Microsoft.ProjectServer.PJClientCallableException","message":{"lang":"en-US","value":"GeneralSecurityAccessDenied"}}}
What could be the possible problem?
I know that my token is correct, as it works for accessing */web/lists. I also know that the url is correct, as I can open it in my browser (providing that I'm logged in into sharepoint)
You need to use a FormDigestValue.
Make a GET call to .../_api/contextinfo and store the value of 'FormDigestValue'. Then for all your other calls, add a header of X-RequestDigest: <FormDigestValue>

javascript how to parse numbers?

Hello so i'm trying to parse numbers that i get once i request page using http web request.But it seems that it fails me every time :/
Code that i use to make web request and parse:
var xhr = new XMLHttpRequest();
xhr.open('GET', "website url", true);
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
alert(response.);
}
}
I don't know what i need to write after dot i tried many options :(
Example of response that i get: {"status":1,"request":"1663758118"}
and i need to get only numbers
Html:
<pre>{"status":1,"request":"1663758118"}</pre>
So if somebody could help that would be great :)
If I understand your question correctly, and your code does correctly parse JSON string into JSON object, then you can do the following to retrieve data from JSON object
response.status // '1' as int
response.request // "1663758118" as string
Hope this answer can help you :)
After dot you need to put the property name in order to get the value.
If you need to convert a string to number you can add a + sign immediately before the string:
var response = JSON.parse('{"status":1,"request":"1663758118"}');
var stat = +response["status"];
var req = +response["request"];
console.log('status is: ' + stat + ' typeof is: ' + typeof stat);
console.log('request is: ' + req + ' typeof is: ' + typeof req);
If you need numbers from your response {"status":1,"request":"1663758118"}, you can use do this
const response = {"status":1,"request":"1663758118"}
const values = Object.keys(response).map(key => parseInt(response[key], 10))
console.log(values) // => [1, 1663758118]

Javascript XML Http request using the Google Custom Search Element api

I am working on a chrome extension that was utilizing the google search api, to return an image from an ajax request. Apparently the api is no longer functional, so I was wondering how I could make a similar request with the Custom Search Element Api. I have pasted the portion of my code that was making the request below.
var logo = function (searchTerm, callback, message, name) {
var searchUrl = 'https://ajax.googleapis.com/ajax/services/search/images' +
'?v=1.0&q=' + encodeURIComponent(searchTerm);
var x = new XMLHttpRequest();
x.open('GET', searchUrl);
// The Google image search API responds with JSON, so let Chrome parse it.
x.responseType = 'json';
x.onload = function() {
// Parse and process the response from Google Image Search.
var response = x.response;
if (!response || !response.responseData || !response.responseData.results ||
response.responseData.results.length === 0) {
console.log( "loading error" )
console.log(response)
console.log(response.responseData)
console.log(response.responseData.results)
}
var firstResult = response.responseData.results[0];
// Take the thumbnail instead of the full image to get an approximately
// consistent image size.
var imageUrl = firstResult.tbUrl;
var width = parseInt(firstResult.tbWidth);
var height = parseInt(firstResult.tbHeight);
console.assert(
typeof imageUrl == 'string' && !isNaN(width) && !isNaN(height),
'Unexpected respose from the Google Image Search API!');
callback(imageUrl, width, height, message, name);
};
x.onerror = function() {
alert("error")
document.writeln("network error");
};
x.send();
}
I have been trying to figure it out by reading the the documentation, but I could definitely use some help.
Here's the link of the docs: Using REST.
You need to create your own Custom Search Engine on google developer console, modify the getImageUrl() method accordingly.
change searchUrl
var searchUrl = 'https://www.googleapis.com/customsearch/v1?' +
'key=' + 'YOUR_KEY' +
'&cx=' + '00000:yourcx' +
'&searchType=image' +
'&q=' + encodeURIComponent(searchTerm);
and modify the response object according to the JSON.
You can refer to this question for how to tweak the console and refine search result.

Categories

Resources