How to dynamically pass a parameter in the get in method? - javascript

In the network tab, I send the query 'https://api.spotify.com/v1/search?limit=14&market=US&offset=5&q=abba&type=track,artist'
It does not work: how to set the query to be in that order:
https://api.spotify.com/v1/search?q=mmm&type=track%2Cartist&market=US&limit=10&o
'q' should be after search?
getArtists(query) {
const params = {
type: 'track,artist',
market: 'US',
limit: 14,
offset: 5
};
if (typeof query === 'string') {
params.q = query;
}
console.log(params)
return this.$http.get("https://api.spotify.com/v1/search", {
params }).then(function mySuccess(response) {
console.log(response.data);
}, function myError(response) {
console.log(response);
});
};
getArtists('Abba');

I see a auhtorization error when trying your apis.
{
"error": {
"status": 401,
"message": "No token provided"
}
}
You need to provide the authorization token in the header to fix this.
getArtists(query) {
let params = {
q: query,
type: 'track,artist',
market: 'US',
limit: 14,
offset: 5
};
if (typeof query !== 'string') {
delete params.q;
}
console.log(params)
return this.$http.get("https://api.spotify.com/v1/search", {headers: {
'Authorization': 'Bearer <AUTHORIZATION TOKEN>},
params }).then(function mySuccess(response) {
console.log(response.data);
}, function myError(response) {
console.log(response);
});
};
If you don't have it yet, check out the process here : https://developer.spotify.com/documentation/general/guides/authorization-guide/

Try this
getArtists(query) {
let params = {
q: query,
type: 'track,artist',
market: 'US',
limit: 14,
offset: 5
};
if (typeof query !== 'string') {
delete params.q;
}
console.log(params)
return this.$http.get("https://api.spotify.com/v1/search", {
params }).then(function mySuccess(response) {
console.log(response.data);
}, function myError(response) {
console.log(response);
});
};

Related

Cannot set property 'status' of undefined

My script is running well but at the end I get an error message Error during script execution.
Cannot set property 'status' of undefined.
Does anybody have a clue what I am doing wrong here?
const fs = require("fs-promise");
const axios = require("axios");
const jsonxml = require("jsonxml");
const tmp = require("tmp");
module.exports = {
mpGetChecklist: async function (mpurl, bearer, systemGetChecklistMethod, systemGetChecklistId, systemGetChecklistDatasetName) {
var getChecklist = {
method: systemGetChecklistMethod,
url: mpurl + "/connector/system/getChecklist?id=" + systemGetChecklistId,
headers: {
Authorization: "Bearer " + bearer,
},
};
let tmpPath = tmp.fileSync({ postfix: ".xml" });
let result;
await axios(getChecklist)
.then(function (response) {
console.log(JSON.stringify(response.data));
let xmlOptions = { header: true, root: "JSON", indent: true };
let xmlString = jsonxml(response.data, xmlOptions);
try {
fs.writeFileSync(tmpPath.name, xmlString);
result = { status: "succes", xmlPath: tmpPath.name, datasetName: systemGetChecklistDatasetName };
} catch (error) {
result = { status: "error", msg: error };
}
})
.catch(function (error) {
console.log(error);
});
return result;
},
};

Async function unexpected behavior

At the moment I am working on an Electron app that is supplied with data via an API. The renderer calls a "backend function", which first gets the API key via Keytar and then executes the API call via axios.
The problem here is that Keytar always returns null/undefined, even if a similar function with the same functionality works without any problems, also because this point can only be reached if a valid API key is stored at all and this will also be queried by Keytar.
I am new to async/await-functions, maybe I didn't get something.
btw: Maybe the title doesn't fit too well, but I was a bit at a loss about this one.
(keytarService, username, baseUrl are globals)
Here is my code:
// Api-calling function
async function makeCall(method_type, url_path, data_array) {
keytar.getPassword(keytarService, username).then((apiKey) => {
if (apiKey == null || apiKey == undefined) {
return false;
}
axios({
method: method_type,
url: baseUrl + url_path,
headers: {
'content-type': 'application/json',
'X-AUTH-TOKEN': apiKey,
},
data: data_array,
}).then(
(response) => {
return response.data;
},
(error) => {
return false;
}
);
});
}
//index_renderer.js
webContents.on('dom-ready', () => {
apiMain
.makeCall('GET', 'user/self')
.then((data) => {
console.log(data);
document.getElementById('username_text').innerText =
data.firstName + '' + data.lastName;
})
.catch((err) => console.log(err));
});
Similar function which is working:
async function isAuthenticated() {
apiKey = await keytar.getPassword(keytarService, username);
if (apiKey == null || apiKey == undefined) {
return false;
}
axios({
method: 'GET',
url: baseUrl + '/api/isAuthenticated',
headers: {
'content-type': 'application/json',
'X-AUTH-TOKEN': apiKey,
},
data: {},
}).then(
(response) => {
console.log(response);
if (!response.data.authenticated) {
logout();
}
return response;
},
(error) => {
console.log(error);
logout();
return error;
}
);
}
// call of the working function in main.js
if (authProcess.isAuthenticated()) {
mainwin.loadFile('index.html');
} else {
mainwin.loadFile('login.html');
}
Thanks in advance.
You are missing important returns in MakeCall().
Try:
function makeCall(method_type, url_path, data_array) {
// return this promise to MakeCall
return keytar.getPassword(keytarService, username).then((apiKey) => {
if (apiKey == null || apiKey == undefined) {
return false;
}
// return this promise to keytar.getPassword then()
return axios({
method: method_type,
url: baseUrl + url_path,
headers: {
'content-type': 'application/json',
'X-AUTH-TOKEN': apiKey,
},
data: data_array,
}).then(
(response) => {
return response.data;
},
(error) => {
return false;
}
);
});
}

Access the `access_token` property in localstorage

I have saved the token in localstorage: localStorage.setItem ('token', JSON.stringify (res.data)). I am trying to access the access_token property.
JSON.parse(localStorage.getItem(token['access_token']))
It gets error: token is undefined;
getToken = () => {
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
const url = '/oauth2/token';
axios({
method: 'post',
url,
data,
config
})
.then(res => {
if (res.status === 200) {
localStorage.setItem('token', JSON.stringify(res.data))
this.setState({
token: res.data
})
} else {
const error = new Error(res.error);
throw error;
}
}).catch(err => {
console.error(err);
alert('error');
});
}
You syntax needs to be corrected to as below
JSON.parse(localStorage.getItem('token'))['access_token']
You can use
var tokenData = JSON.parse(localStorage.getItem('token'));
console.log(tokenData.access_token);
Example how to store object in localStorage
var myObj = {
one: {
title: 'first',
id: 1,
customKey : {
first: "first",
second: "second"
}
},
two: {
title: 'second',
id: 2
},
three: {
title: 'this is the third',
id: 3
}
};
localStorage.setItem('storeObj', JSON.stringify(myObj));
var getObject = JSON.parse(localStorage.getItem('storeObj'));

Call to Factory-defined method returning undefined value/promise

I have an intricate and complex (not my code) factory call in Angular that when used, doesn't return a then property or anything that can be used to run a successCallback method (error itself is TypeError: Cannot read property 'then' of undefined). I'm not sure what the cause could be, but there are quite a few unique components of the call that could be the cause, such as the multiple nested $http.post calls to the Web Service.
updateDocument: function(documentId, newFileData, appointmentFileName = null, appointmentCategory = null, appointmentId = null) {
//Get Existing Document Details (including Revision)
//document.
documentsService.documentsFactory.getDocumentRecordById(documentId).then(
function successCallback(response) {
console.debug("Response", response);
var NextRevision = parseInt(response.data.revision) + 1;
if ((appointmentCategory === null) || (appointmentCategory === undefined)) {
appointmentCategory = response.data.category_id;
}
if ((appointmentId === null) || (appointmentId === undefined)) {
var ErrorObj = {
status: 10,
message: 'Appointment ID not defined.'
};
return ErrorObj;
}
if ((appointmentFileName === null) || (appointmentFileName === undefined)) {
appointmentFileName = response.data.filename;
}
if ((newFileData === null) || (newFileData === undefined)) {
var ErrorObj = {
status: 11,
message: 'File Data not defined.'
};
return ErrorObj;
}
var action = 'set_document_revision';
var endpoint = cfg.url;
var sessionId = systemService.sessionService.getSessionId();
var DocRevObj = {
session: sessionId,
document_revision: {
id: documentId,
file: newFileData,
filename: appointmentFileName,
revision: NextRevision
}
};
var DocNodeObj = {
session: sessionId,
module: "Documents",
name_value_list: [{
name: 'document_name',
value: appointmentFileName
}, {
name: 'category_id',
value: appointmentCategory
}, {
name: 'id',
value: documentId
}]
};
var RevisionRequestParams = {
method: action,
input_type: "JSON",
response_type: "JSON",
rest_data: DocRevObj
};
var NodeRequestParams = {
method: "set_entry",
input_type: "JSON",
response_type: "JSON",
rest_data: DocNodeObj
}
var headers = {
"Content-Type": "application/json"
};
return $http.post(endpoint, RevisionRequestParams, headers).then(
function successCallback(response2) {
console.debug("Successfully Replaced File", response2);
//Re-adjust the File Entry to match new changes
//(make a call to set_entry)
return $http.post(endpoint, NodeRequestParams, headers).then(
function successCallback(response3) {
console.debug("Successfully Updated File", response3);
return response3;
},
function errorCallback(response3) {
console.debug("Error", response3);
return response3
}
);
return response2;
},
function errorCallback(response2) {
console.debug("Error", response2);
return response2;
}
);
console.debug("Success", response);
return response;
}, function errorCallback(response) {
console.debug("Error", response);
return response;
}
);
}
The referring method call (inside a Controller, fired on a click event)
appointmentsService.appointmentsFactory.updateDocument(CurrentDocumentId, result, NewFileName, NewDocumentType, CurrentAppointmentID).then(
function successCallback(response) {
//Success Callback Logic
},
function errorCallback(response) {
});
Is it possible that in fact, the call for updateDocument is getting a return long before the Promises send anything back? If so, what are my options to work around it?
Your updateDocument function doesn't return anything. Add return before the getDocumentRecordById call.
var updateDocument = function(documentId, newFileData, appointmentFileName = null, appointmentCategory = null, appointmentId = null) {
//Get Existing Document Details (including Revision)
//document.
return documentsService.documentsFactory.getDocumentRecordById(documentId).then(
...
You need to return the promise object like this:
updateDocument: function(documentId, newFileData, appointmentFileName = null, appointmentCategory = null, appointmentId = null) {
//Get Existing Document Details (including Revision)
//document.
return documentsService.documentsFactory.getDocumentRecordById(documentId).then(
function successCallback(response) {
console.debug("Response", response);
var NextRevision = parseInt(response.data.revision) + 1;
if ((appointmentCategory === null) || (appointmentCategory === undefined)) {
appointmentCategory = response.data.category_id;
}
if ((appointmentId === null) || (appointmentId === undefined)) {
var ErrorObj = {
status: 10,
message: 'Appointment ID not defined.'
};
return ErrorObj;
}
if ((appointmentFileName === null) || (appointmentFileName === undefined)) {
appointmentFileName = response.data.filename;
}
if ((newFileData === null) || (newFileData === undefined)) {
var ErrorObj = {
status: 11,
message: 'File Data not defined.'
};
return ErrorObj;
}
var action = 'set_document_revision';
var endpoint = cfg.url;
var sessionId = systemService.sessionService.getSessionId();
var DocRevObj = {
session: sessionId,
document_revision: {
id: documentId,
file: newFileData,
filename: appointmentFileName,
revision: NextRevision
}
};
var DocNodeObj = {
session: sessionId,
module: "Documents",
name_value_list: [{
name: 'document_name',
value: appointmentFileName
}, {
name: 'category_id',
value: appointmentCategory
}, {
name: 'id',
value: documentId
}]
};
var RevisionRequestParams = {
method: action,
input_type: "JSON",
response_type: "JSON",
rest_data: DocRevObj
};
var NodeRequestParams = {
method: "set_entry",
input_type: "JSON",
response_type: "JSON",
rest_data: DocNodeObj
}
var headers = {
"Content-Type": "application/json"
};
return $http.post(endpoint, RevisionRequestParams, headers).then(
function successCallback(response2) {
console.debug("Successfully Replaced File", response2);
//Re-adjust the File Entry to match new changes
//(make a call to set_entry)
return $http.post(endpoint, NodeRequestParams, headers).then(
function successCallback(response3) {
console.debug("Successfully Updated File", response3);
return response3;
},
function errorCallback(response3) {
console.debug("Error", response3);
return response3
}
);
return response2;
},
function errorCallback(response2) {
console.debug("Error", response2);
return response2;
}
);
console.debug("Success", response);
return response;
}, function errorCallback(response) {
console.debug("Error", response);
return response;
}
);
}
You should return the factory object based on your code.
Example...
app.factory('factoryName', function() {
var factoryObj= {
save: function() {
},
update: function() {
}
};
return factoryObj; //return object
});
You can return your code like below.
return {
updateDocument: function(documentId, newFileData, appointmentFileName = null, appointmentCategory = null, appointmentId = null) {
//Get Existing Document Details (including Revision)
//document.
documentsService.documentsFactory.getDocumentRecordById(documentId).then(
function successCallback(response) {
console.debug("Response", response);
var NextRevision = parseInt(response.data.revision) + 1;
if ((appointmentCategory === null) || (appointmentCategory === undefined)) {
appointmentCategory = response.data.category_id;
}
if ((appointmentId === null) || (appointmentId === undefined)) {
var ErrorObj = {
status: 10,
message: 'Appointment ID not defined.'
};
return ErrorObj;
}
if ((appointmentFileName === null) || (appointmentFileName === undefined)) {
appointmentFileName = response.data.filename;
}
if ((newFileData === null) || (newFileData === undefined)) {
var ErrorObj = {
status: 11,
message: 'File Data not defined.'
};
return ErrorObj;
}
var action = 'set_document_revision';
var endpoint = cfg.url;
var sessionId = systemService.sessionService.getSessionId();
var DocRevObj = {
session: sessionId,
document_revision: {
id: documentId,
file: newFileData,
filename: appointmentFileName,
revision: NextRevision
}
};
var DocNodeObj = {
session: sessionId,
module: "Documents",
name_value_list: [{
name: 'document_name',
value: appointmentFileName
}, {
name: 'category_id',
value: appointmentCategory
}, {
name: 'id',
value: documentId
}]
};
var RevisionRequestParams = {
method: action,
input_type: "JSON",
response_type: "JSON",
rest_data: DocRevObj
};
var NodeRequestParams = {
method: "set_entry",
input_type: "JSON",
response_type: "JSON",
rest_data: DocNodeObj
}
var headers = {
"Content-Type": "application/json"
};
return $http.post(endpoint, RevisionRequestParams, headers).then(
function successCallback(response2) {
console.debug("Successfully Replaced File", response2);
//Re-adjust the File Entry to match new changes
//(make a call to set_entry)
return $http.post(endpoint, NodeRequestParams, headers).then(
function successCallback(response3) {
console.debug("Successfully Updated File", response3);
return response3;
},
function errorCallback(response3) {
console.debug("Error", response3);
return response3
}
);
return response2;
},
function errorCallback(response2) {
console.debug("Error", response2);
return response2;
}
);
console.debug("Success", response);
return response;
}, function errorCallback(response) {
console.debug("Error", response);
return response;
}
);
}
}

Ajax post, converts array of numbers to array of strings

Im trying to do a post from a .ejs page to a nodejs api.
this is the call i do
var dataSend={
from:from,
to:to,
datesStart: startDates,
datesEnd: endDates,
price: totalPriceOften,
places:JSON.stringify(placesArray),
package: pSizeOften,
transport: $('.activeFilter:eq(1) a').html().toLowerCase(),
pickupRange: pFlexOften,
dropRange: dFlexOften,
};
$.ajax({
url: location.origin + '/publishTravelOften',
headers: {
apiKey: APIKEYWEB
},
type: "POST",
data: dataSend,
dataType: "json",
async: true,
success: function (data) {
//do stuff
},
error: function (err) {
//do other stuff
}
});
the data i send is a object with this information
and in the nodejs api, i have this:
router.post('/publishTravelOften', function (req, res) {
if(req.user == null || req.user == undefined){
res.status(403).send(Error.ERROR_NO_USER);
}
else {
var time = Date.now();
var userLanguage = Geo.getCountry(req);
console.log("LOAD TIME /publishTravelOften: " + (Date.now() - time));
Config.setCountry(Geo.getCountry(req));
publishTravelOften(req, function (error, data) {
if (!error) {
data.lang = Lang.getLang(userLanguage);
data.socketUrl = Config.getSocketUrl();
data.apiUrl = Config.getApiUrlWeb();
res.send(data);
}
else {
res.status(500).send(error);
}
});
}
});
function publishTravelOften(req,callback){
console.log("########");
console.log(req.body);
console.log("########");
var url = Config.getApiUrlWeb() + "travel/often/create?user="+req.user._id+"&currency="+Geo.getCountry(req);
var options = {
url: url,
form:req.body,
headers: {
'apikey': Config.getAPIKeyWeb()
},
};
request.post(options, function (error, response, body) {
var parsedResponse = JSON.parse(body);
if (parsedResponse.success == false)
callback(parsedResponse, parsedResponse);
else {
var data = {
newTravel: parsedResponse.data
};
callback(error, data);
}
});
}
my problem is that when i print the data i get on the nodejs part, i have this
{ from: 'ChIJO_PkYRozGQ0R0DaQ5L3rAAQ',
to: 'ChIJ9xUaAY73vEcRUt8vzFOSk1w',
'datesStart[]': [ '1471683240000', '1471596840000' ],
'datesEnd[]': [ '1471683240000', '1471596840000' ],
price: '134.93',
places: '[]',
package: 'medium',
transport: 'airplane',
pickupRange: '15',
dropRange: '5' }
the number arrays get converted to string arrays, also the field names change from datesStart and datesEnd to 'datesStart[]' and 'datesEnd[]'
is this normal? and how can i prevent the arrays from change from number to string arrays?

Categories