I'm trying to get the summary of a random article using the Wikipedia API, but for some reason when parsing the JSON, I run into this error about a quarter of the time:
Unexpected token < in JSON at position 0. Why is this happening? I've pasted the link into my browser manually multiple times and haven't seen anything wrong with the JSON string.
const articleCount = 10;
const fetch = require('sync-fetch');
function article()
{
return fetch('https://en.wikipedia.org/api/rest_v1/page/random/summary').json().extract;
}
var source = '';
for(let i = 0; i < articleCount; i++)
{
source += article() + ' ';
console.log(parseInt(i/articleCount * 100) + '%');
}
console.log(source);
I've switched out the .json() method with JSON.parse(string), but it has the same problem.
I have to call multiple API using promise all in for loop but I am getting a response in unsequential format. e.g. I have 3 rows but getting a response in 1,2,3 sequence. First getting the first-row response than 3rd row and then getting 2nd row but I need to get a response in a sequential format like (1 row,2 rows,3 rows).
result = '{"error_code":0,"err_desc":null,"data":[{"":"","name":"OTT, KATHRYN M","address":"3110 Horseshoe Trl, Glenmoore, PA","email":"","phone1":"(410) 599-2212","phone2":"(610) 827-9107","phone3":"(610) 308-4566","phone4":"(610) 506-1121","phone5":"(610) 469-0737","phone6":"(610) 942-4347","phone7":"323-7898","phone8":"(814) 371-6133","phone9":""},{"":"","name":"BELTRANTE, SUSAN E","address":"3 Rhoads Ave, Moorestown, NJ\"","email":"SUSAN.BELTRANTE#AOL.COM, JOE.BARGER#YAHOO.COM,","phone1":"(856) 266-0381","phone2":"(856) 273-0869","phone3":"(609) 266-0381","phone4":"(856) 235-3933","phone5":"","phone6":"","phone7":"","phone8":"","phone9":""},{"":"","name":"Manish","address":"4895 E American Beauty Dr, Tucson, AZ 85756","email":"abc#gmail.com","phone1":"(857) 266-0381","phone2":"(857) 273-0869","phone3":"(610) 266-0381","phone4":"(857) 235-3933","phone5":"","phone6":"","phone7":"","phone8":"","phone9":""}]}';
var i;
for (i = 0; i < result.length; i++)
//for (i = 0; i <= 0; i++)
{
var phone = result[i].phone9;
var name = result[i].name;
var address = result[i].address;
var email = result[i].email;
var phone1 = result[i].phone1;
var phone2 = result[i].phone2;
var phone3 = result[i].phone3;
var phone4 = result[i].phone4;
var phone5 = result[i].phone5;
var phone6 = result[i].phone6;
var phone7 = result[i].phone7;
var phone8 = result[i].phone8;
var addressinfo = address.split(',');
var street = addressinfo[0];
var city = addressinfo[1];
var state = addressinfo[2];
var zip = addressinfo[3];
Promise.all([
fetch('https://backend.mioym.properties/api/247/eppraisal?street='+street+'&zip='+zip),
fetch('https://backend.mioym.properties/api/247/zillow?street='+street+'&zip='+zip),
fetch('https://backend.mioym.properties/api/247/pennymac?address='+address),
fetch('https://backend.mioym.properties/api/247/chase?address='+address),
fetch('https://backend.mioym.properties/api/247/realtor?address='+address)
]).then(function (responses) {
// Get a JSON object from each of the responses
return Promise.all(responses.map(function (response) {
console.log("here"+i);
//console.log(response.json());
console.log(response.url);
return response.json();
}));
}).then(function (data) {
console.log("success"+i);
// Log the data to the console
// You would do something with both sets of data here
console.log(data);
}).catch(function (error) {
console.log("error"+i);
// if there's an error, log it
console.log(error);
});
}
So please anyone suggest me solution.
The second Promise.all inside your then block is not necessary, as responses will already contain the resolved values. Note that Promise.all processes the requests in parallel but the resolved responses will be in order. So you can simply do:
Promise.all([
fetch('https://backend.mioym.properties/api/247/eppraisal?street=' + street + '&zip=' + zip),
fetch('https://backend.mioym.properties/api/247/zillow?street=' + street + '&zip=' + zip),
fetch('https://backend.mioym.properties/api/247/pennymac?address=' + address),
fetch('https://backend.mioym.properties/api/247/chase?address=' + address),
fetch('https://backend.mioym.properties/api/247/realtor?address=' + address)
]).then(function (responses) {
// Get a JSON object from each of the responses
return responses.map(function (response) {
console.log(response.url);
return response.json();
});
});
i have a promise that resolves a JSON object with some config data. i want to access this data upon pressing the "send config" button in my HTML client. the communication is done through a websocket connection in nodejs. so the websocket server receives a message that says "send config" from the client and the server is supposed to respond with the config.
code:
showMsg = function (MSGOBJ) {
var parsedOBJ = JSON.parse(MSGOBJ);
//console.log(parsedOBJ.content);
for (var i = 0; i < connections.length; i++) {
switch(parsedOBJ.type) {
case "text":
console.log("Received: " + parsedOBJ.content)
connections[i].sendUTF('{ "type":"text", "content":"Server ready."}')
break;
case "config":
console.log("Received:1 " + parsedOBJ.content)
console.log("Sending config" )
var getConfig = KRequests.getKConfig;
var configOBJ;
getConfig.then(function(result) {
configOBJ = result
});
connections[i].send('{ "type":"config", "content":'+JSON.stringify(configOBJ)+'}');
break;
}
}
}
i know configOBJ would be undefined if i use it outside of the chain, but just to give you an idea of what i want to do. and also if i move the send() inside the chain, it would cause this error: "UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined"
You have two issue one is that you should use:
getConfig.then(function(result) {
console.log(connections[i])
connections[i].send('{ "type":"config", "content":'+JSON.stringify(configOBJ)+'}');
});
The other is that:
for (var i = 0; i < connections.length; i++) {
should be:
for (let i = 0; i < connections.length; i++) {
Or if you don't have let which you should if you are using a recent node that supports more than ES5. You will have to use a IIFE like this:
for (var i = 0; i < connections.length; i++) {
(function (i) {
// put the loop body here
})(i);
}
I am trying to get list product with a keyword using ebay api maintained Here
using following code
var params = {};
params.keywords = ["Canon"];
params.outputSelector = [ 'AspectHistogram' ];
params['paginationInput.entriesPerPage'] = 10;
var filters = {};
filters.itemFilter = [
new ebay.ItemFilter("FreeShippingOnly", true)
];
filters.domainFilter = [
new ebay.ItemFilter("domainName", "Digital_Cameras")
];
ebay.ebayApiGetRequest({
serviceName: 'FindingService',
opType: 'findItemsByKeywords',
appId: '*********************', // FILL IN YOUR OWN APP KEY, GET ONE HERE: https://publisher.ebaypartnernetwork.com/PublisherToolsAPI
params: params,
filters: filters,
parser: ebay.parseItemsFromResponse // (default)
},
// gets all the items together in a merged array
function itemsCallback(error, items) {
if (error) throw error;
console.log('Found', items.length, 'items');
for (var i = 0; i < items.length; i++) {
console.log('- ' + items[i].title);
}
}
);
Which throws following error when called
Error: Bad response status code 500
{
"errorMessage":[{
"error":[{"errorId":["5006"],
"domain":["CoreRuntime"],
"severity":["Error"],
"category":["System"],
"message":["Unable to create xml stream reader for JSON: payload format incorrect or payload is empty"],
"subdomain":["Comm_Recv"],
"parameter":[{"#name":"Param1","__value__":"JSON"}]}]
}]
}
Show the code of api import.
May be a problem there...
try
var ebay = require('ebay-api');
I have the following api :
for (var index in workload.elements) {
(function(index) {
var arr = [];
var resourceIdentifiers = {};
var elementinfo = {};
var metadataModified = {};
elementinfo = workload.elements[index];
arr[index] = workload.elements[index].uri;
if (workload.elements[index].parameters.imageUri) {
arr.push(workload.elements[index].parameters.imageUri);
}
resourceIdentifiers = arr.join(',');
console.log('uri' + resourceIdentifiers);
mysql.elementlevelpricing(resourceIdentifiers, function(result) {
elementlevelpricingSummary = result;
metadataModified = workload.elements[index].metadata;
metadataModified.pricingsummary = elementlevelpricingSummary;
delete elementinfo.metadata;
elementinfo.metadata = metadataModified;
workloadinfo.elements = JSON.stringify(elementArray, null, 2);
elementArray[index] = elementinfo;
console.log(JSON.stringify(elementArray, null, 2));
res.send(JSON.stringify(elementArray, null, 2));
});
})(index);
}
console.log prints the correct result , but the response to the REST call is incorrect and getting the result of only one the value getting into the loop.
First off, use a forEach or map instead of a for loop with IIFEs.
Second, an HTTP request only has one response. You can't send multiple requests with res.send firing off a few times. If you want all of the information, just aggregate the results of JSON.stringify(elementArray, null, 2) and send the final aggregated data with res.send.