API-key format invalid Binance Api - javascript

I'm having a problem wanting to get priceIndex information on binance. This is the error I got when accessing it.
{"code":-2014,"msg":"API-key format invalid."}
The URL I use is this:
https://api.binance.com/sapi/v1/margin/priceIndex?symbol=BNBBTC&recvWindow=5000&timestamp=1592407054950&signature=xxxxxxxx
<script>
export default {
data() {
return {
binance: {
restapi: {
apiUrl: 'https://api.binance.com',
endPoint: '/sapi/v1/margin/priceIndex',
method: 'GET',
},
config: {
apiKey: 'xxxxxxxxx',
secretKey: 'xxxxxxxxx',
},
},
formData: {
symbol: 'BNBBTC',
recvWindow: '5000',
timestamp: '',
}
}
},
methods: {
getTime(){
var vm = this;
vm.$http({
url: 'https://api.binance.com/api/v1/time',
method: 'GET',
}).then((res) => {
vm.formData.timestamp = res.body.serverTime;
}).catch((err) => {
//error
});
},
mainProcces(){
var vm = this;
const CryptoJS = require('crypto-js');
const qs = require('qs');
const dataQueryString = qs.stringify(vm.formData);
const dataSignature = CryptoJS.HmacSHA256(dataQueryString, vm.binance.config.secretKey).toString(CryptoJS.enc.Hex);
vm.requestData(vm.binance.restapi, vm.binance.config, dataQueryString, dataSignature);
},
requestData(restApi, config, dataStr, signature){
var vm = this;
vm.$http({
url: restApi.apiUrl+restApi.endPoint+'?'+dataStr+'&signature='+signature,
headers: {
'X-MBX-APIKEY': config.apiKey,
},
method: restApi.method,
}).then((res) => {
// success
}).catch((error) => {
// error
});
},
},
mounted() {
var vm = this;
vm.getTime();
setTimeout(function(){
vm.mainProcces();
}, 1000);
}
}
</script>

Related

Firestore getSignedUrl() give The caller does not have permission at Gaxios

I got following error at file.getSignedUrl. I have other function to copy the file and create new file on Cloud Storage. Why this function need permission and where do I need to set?
Error: The caller does not have permission at Gaxios._request (/layers/google.nodejs.yarn/yarn_modules/node_modules/gaxios/build/src/gaxios.js:129:23) at runMicrotasks () at processTicksAndRejections (node:internal/process/task_queues:96:5) at async Compute.requestAsync (/layers/google.nodejs.yarn/yarn_modules/node_modules/google-auth-library/build/src/auth/oauth2client.js:368:18) at async GoogleAuth.signBlob (/layers/google.nodejs.yarn/yarn_modules/node_modules/google-auth-library/build/src/auth/googleauth.js:662:21) at async sign (/layers/google.nodejs.yarn/yarn_modules/node_modules/#google-cloud/storage/build/src/signer.js:103:35) { name: 'SigningError' }
const functions = require("firebase-functions");
const axios = require("axios");
const { Storage } = require("#google-cloud/storage");
const storage = new Storage();
// Don't forget to replace with your bucket name
const bucket = storage.bucket("projectid.appspot.com");
async function getAlbums() {
const endpoint = "https://api.mydomain.com/graphql";
const headers = {
"content-type": "application/json",
};
const graphqlQuery = {
query: `query Albums {
albums {
id
album_cover
}
}`,
};
const response = await axios({
url: endpoint,
method: "post",
headers: headers,
data: graphqlQuery,
});
if (response.errors) {
functions.logger.error("API ERROR : ", response.errors); // errors if any
} else {
return response.data.data.albums;
}
}
async function updateUrl(id, url) {
const endpoint = "https://api.mydomain.com/graphql";
const headers = {
"content-type": "application/json",
};
const graphqlQuery = {
query: `mutation UpdateAlbum($data: AlbumUpdateInput!, $where:
AlbumWhereUniqueInput!) {
updateAlbum(data: $data, where: $where) {
id
}
}`,
variables: {
data: {
album_cover: {
set: url,
},
},
where: {
id: id,
},
},
};
const response = await axios({
url: endpoint,
method: "post",
headers: headers,
data: graphqlQuery,
});
if (response.errors) {
functions.logger.error("API ERROR : ", response.errors); // errors if any
} else {
return response.data.data.album;
}
}
const triggerBucketEvent = async () => {
const config = {
action: "read",
expires: "03-17-2025",
};
const albums = await getAlbums();
albums.map((album) => {
const resizedFileName = album.id + "_300x200.webp";
const filePath = "images/albums/thumbs/" + resizedFileName;
const file = bucket.file(filePath);
functions.logger.info(file.name);
file.getSignedUrl(config, function (err, url) {
if (err) {
functions.logger.error(err);
return;
} else {
functions.logger.info(
`The signed url for ${resizedFileName} is ${url}.`
);
updateUrl(album.id, url);
}
} );
});
};
exports.updateResizedImageUrl = functions.https.onRequest(async () => {
await triggerBucketEvent();
});
I need to add Service Account Token Creator role for App Engine default service account.

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;
},
};

How to keep line breaks in POST message

When i get the content of an email it is formatted with line breaks but when i send it to the API the result is text with no white space.
Is there any way to keep the spacing?
Edit:
const postNewTask = (taskTitle, taskComment, workerId) => {
const { projectId, tasklistId } = dataStore();
const { userEmail, apiKey } = credentialsStore();
const options = {
method: 'POST',
headers: {
Authorization:
'Basic ' + Utilities.base64Encode(`${userEmail}:${apiKey}`),
},
};
if (taskComment && workerId) {
options.payload = JSON.stringify({
name: taskTitle,
comment: {
content: taskComment,
},
worker: parseInt(workerId),
});
}
I solved it. I just had to use taskComment.replace(/(?:\r\n|\r|\n)/g, '<br>') and the API knew what to do from there.
Final working code:
const postNewTask = (taskTitle, taskComment, workerId) => {
const { projectId, tasklistId } = dataStore();
const { userEmail, apiKey } = credentialsStore();
const options = {
method: 'POST',
headers: {
Authorization:
'Basic ' + Utilities.base64Encode(`${userEmail}:${apiKey}`),
},
};
if (taskComment && workerId) {
options.payload = JSON.stringify({
name: taskTitle,
comment: {
content: taskComment.replace(/(?:\r\n|\r|\n)/g, '<br>'),
},
worker: parseInt(workerId),
});

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'));

MEAN stack app using Meetup.api - "Meetup.getCategories is not a function"?

I'm using the Meetups.com API in my node app, and I'm trying to return a JSON list of all of the event categories, but Angular keeps returning, "angular.js:13708 TypeError: Meetup.getCategories is not a function"
Here's my controller for the events page:
angular
.module("Londate")
.controller("EventsController", EventsController);
EventsController.$inject = ["$state", "TokenService", "$rootScope", "Meetup"];
function EventsController($state, TokenService, $rootScope, Meetup) {
var self = this;
this.mapCenter = { lat: 51.5, lng: -0.1 };
this.category = 1;
this.allCategories = [];
this.all = [];
navigator.geolocation.getCurrentPosition(function(position) {
$rootScope.$evalAsync(function() {
self.mapCenter = {
lat: position.coords.latitude,
lng: position.coords.longitude
}
self.getEvents();
});
});
this.getEvents = function() {
Meetup.getEvents({
lat: self.mapCenter.lat,
lng: self.mapCenter.lng,
category: self.category
})
.then(function(events) {
console.log("EVENTS: " + events);
self.all = events;
})
}
this.getCategories = function() {
Meetup.getCategories({
name: self.name
})
.then(function(categories){
console.log("CATEGORIES: " + categories);
self.allCategories = categories;
})
}
self.getCategories();
}
And the Meetup.js controller on the backend:
var request = require('request-promise');
function getEvents(req, res) {
request.get({
url: "https://api.meetup.com/2/open_events",
qs: {
key: process.env.MEETUP_API_KEY,
lat: req.query.lat,
lon: req.query.lng,
category: req.query.category,
radius: req.query.radius || 1,
sign: true
},
json: true
})
.then(function(response) {
res.status(200).json(response.results);
console.log(response);
})
.catch(function(err) {
console.log(err);
res.status(500).json(err);
})
}
function getCategories(req, res) {
request.get({
url: "https://api.meetup.com/2/categories",
qs: {
key: process.env.MEETUP_API_KEY,
name: req.query.name,
sign: true
},
json: true
})
.then(function(response) {
res.status(200).json(response.results);
console.log(response);
})
.catch(function(err) {
console.log(err);
res.status(500).json(err);
})
}
module.exports = {
getEvents: getEvents,
getCategories: getCategories
}
And the meetup.js service on the frontend:
angular
.module("Londate")
.service("Meetup", Meetup)
Meetup.inject = ["$http"];
function Meetup($http) {
this.getEvents = function(params) {
return $http({
method: "GET",
url: "/api/meetups",
params: params
})
.then(function(res) {
return res.data;
});
};
}
Thanks!
Solved! I neglected to include getCategories in the service, as such:
angular
.module("Londate")
.service("Meetup", Meetup)
Meetup.inject = ["$http"];
function Meetup($http) {
this.getEvents = function(params) {
return $http({
method: "GET",
url: "/api/meetups/events",
params: params
})
.then(function(res) {
return res.data;
});
};
this.getCategories = function() {
return $http({
method: "GET",
url: "/api/meetups/categories"
})
.then(function(res) {
return res.data;
});
}
}

Categories