I am working on a project that I have to authenticate e get a token from API body content.
How can I Get only the access_token and save it on a variable to use in another API?
I tried too many things to access it. I think it´s something very easy to do, but I don´t know how!
I am new in node/typescript.
Thank you!
Result:
{
"access_token": "eyJhbGciOiJSUzUxMiIAU6l9z2zMQiI9g",
"refresh_token": "AFGpstweytwtewetwetwetwetwetwet2Fg",
"scope": "default",
"token_type": "Bearer",
"expires_in": 3600
}
export const chamada = (event, context, callback) => {
var request = require('request');
console.log('fora');
request.post('http://MY_API',
{ json: { key: 'value' } },
function (error, response, body) {
if (!error && response.statusCode == 201) {
console.log('dentro');
console.log(body);
}
else {
console.log(response.statusCode);
}
}
);
const p = new Promise((resolve) => {
resolve('success');
});
p.then(() =>
callback(null, {
message: 'Go Serverless Webpack (Ecma Script) v1.0! First module!',
event,
})
).catch((e) => callback(e));
};
You have to read the property from the response. Inside of the first if in the callback, you can just access body.access_token and do whatever you like with it.
Not sure I understand what you mean by "use it in another api". Maybe you can add more description on how you want to use it?
By the way, I see that the library that you are using (request) is marked as deprecated, so if possible, you might want to replace it.
Related
I am making a Discord bot, and I want it to be able to use the YouTube API to fetch new uploads from a specific channel.
I have searched elsewhere, but they all say how to upload videos, not how to track uploads.
Is this possible, and how can I do it?
Edit: Tried PubSubHubbub but it was very confusing and I couldn't get it to work
Here an example built on top of Node.js (v12) and Fastify and published with ngrok:
I wrote some comments explaining what it is happening:
const fastify = require('fastify')({ logger: true })
const xmlParser = require('fast-xml-parser')
const { URLSearchParams } = require('url')
const fetch = require('node-fetch')
// add an xml parser
fastify.addContentTypeParser('application/atom+xml', { parseAs: 'string' }, function (req, xmlString, done) {
try {
const body = xmlParser.parse(xmlString, {
attributeNamePrefix: '',
ignoreAttributes: false
})
done(null, body)
} catch (error) {
done(error)
}
})
// this endpoint needs for authentication
fastify.get('/', (request, reply) => {
reply.send(request.query['hub.challenge'])
})
// this endpoint will get the updates
fastify.post('/', (request, reply) => {
console.log(JSON.stringify(request.body, null, 2))
reply.code(204)
reply.send('ok')
})
fastify.listen(8080)
.then(() => {
// after the server has started, subscribe to the hub
// Parameter list: https://pubsubhubbub.github.io/PubSubHubbub/pubsubhubbub-core-0.4.html#rfc.section.5.1
const params = new URLSearchParams()
params.append('hub.callback', 'https://1f3dd0c63e78.ngrok.io') // you must have a public endpoint. get it with "ngrok http 8080"
params.append('hub.mode', 'subscribe')
params.append('hub.topic', 'https://www.youtube.com/xml/feeds/videos.xml?channel_id=UCfWbGF64qBSVM2Wq9fwrfrg')
params.append('hub.lease_seconds', '')
params.append('hub.secret', '')
params.append('hub.verify', 'sync')
params.append('hub.verify_token', '')
return fetch('https://pubsubhubbub.appspot.com/subscribe', {
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: params,
method: 'POST'
})
})
.then((res) => {
console.log(`The status must be 204. Received ${res.status}`)
// shows the error if something went wrong
if (res.status !== 204) {
return res.text().then(txt => console.log(txt))
}
})
I used my channel id to do some testing, consider that the notification is not in real-time, the POSTs are triggered after several minutes usually.
I'm trying to write a plugin for HomeBridge and have run in to a problem. I started out by just writing some code, start up Homebridge and test it. That worked out find in the beginning but after a while as I added more functionality every time I start HomeBridge there's a lot of testing just to ensure that I haven't broken anything. I mainly work with Java and have just started out with JavaScript. I have copied the patten on how the plugin should be designed. Theres very little documentation about how to write a plugin so I'm kind of in the dark here when it comes to best practice and so on. I have simplified the code so it won't take that much space but the structure is intact. So my question is: How do I test this code?
index.js
let Service, Characteristic;
let request = require('request');
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory("homebridge-myplugin", "MyPlugin", MyPluginDevice);
};
function MyPluginDevice(log, config) {
this.log = log;
this.url = config['url'];
this.id = config['id'];
}
MyPluginDevice.prototype = {
getSwitchOnCharacteristic: function(callback) {
this.httpRequest(this.url, null, 'GET', function(error, response, body) {
if (error) {
this.log("Fail: %s", error.message);
callback(error);
} else {
const newState = body['state'];
return callback(null, newState);
}
}.bind(this)
);
},
setSwitchOnCharacteristic: function(state, callback) {
this.httpRequest(this.url, requestBody, 'POST', function(error, response, body) {
if (error) {
this.log("Fail: %s", error.message);
callback(error);
} else {
callback();
}
}.bind(this));
},
httpRequest: function(url, body, theMethod, callback) {
request(
{
url: url,
body: body,
method: theMethod,
auth: {
user: 'nexa',
pass: 'nexa',
sendImmediately: false
},
json: true
},
function(error, response, body) {
callback(error, response, body)
})
},
getServices: function() {
let informationService = new Service.AccessoryInformation();
informationService.setCharacteristic(Characteristic.Manufacturer, "My Nexa plugin").setCharacteristic(Characteristic.Model, "My Nexa Plugin Model").setCharacteristic(Characteristic.SerialNumber, "A very special number");
this.switchService = new Service.Switch(this.name);
this.switchService
.getCharacteristic(Characteristic.On)
.on("get", this.getSwitchOnCharacteristic.bind(this))
.on("set", this.setSwitchOnCharacteristic.bind(this));
return [this.switchService];
}
};
After having been at it for a while I can't write a test for this code. I'm having problem with variables being null and however I try to get around it I always end up with some part of the code not initiated. I have tried:
let MyPluginDevice = require('./index');
let myDevice = new MyPluginDevice(homebridgeMock);
but that leaves me with a problem with getSwitchOnCharacteristic and setSwitchOnCharacteristic. My other approach is to access the MyPluginDevice through my homebridgeMock. But that leaves me with getSwitchOnCharacteristic and setSwitchOnCharacteristicas null or not a function.
I'm kind of out of ideas and my skills is not that good so I can spot the problem or of I have implemented the code in a way that it can't be tested. I got no idea how other developers have done when writing a plugin but I would feel much safer if I could have a few tests running.
Help me Stackoverflow, you are my only hope!
First of all,I am using the blaze tier, so no issue of billing.
I have also included
"request" : "*"
in package.json dependencies.
Look at my code index.js in the inline editor:
`
'use strict';
var global_request = require('request');
var myJSONObject = {
"limit": 10,
"offset": 0,
"query": "example"
};
global_request.post(
'https://example.com', {
json: myJSONObject },
function (error, res, body) {
if (!error && res.statusCode == 200) {
console.log(res);
console.log(body);
}
}
);
`
But in the firebase log I am getting the following error:
Unhandled rejection
Error: Can't set headers after they are sent.
I followed How to make an HTTP POST request in node.js? for help. But the code still has errors.
What am I doing wrong here?? Thanks for help.
The Dialogflow library assumes that you're using Promises if you're doing asynchronous operations.
Typically, instead of using the request library, I use the request-promise-native library. So that block of code might look something like this:
var rp = require('request-promise-native');
var myJSONObject = {
"limit": 10,
"offset": 0,
"query": "example"
};
var options = {
method: 'post',
uri: 'https://example.com',
body: myJSONObject,
json: true
};
return rp( options )
.then( body => {
console.log( body );
// This is also where you'd call the library
// to send a reply.
return Promise.resolve( true );
})
.catch( err => {
// You should also return a message here of some sort
return Promise.resolve( true );
});
Trying to wrap my head around what this error really means, but it's saying Anonymous caller does not have storage.objects.get access to... when I try to get fileData from a bucket file.
app.get('/api/videos', (req, res) => {
const storageBucket = storageClient.bucket(config.video_bucket);
storageBucket.getFiles(function(err, files) {
if (!err) {
let fileArray = [];
files.forEach(function(file) {
const videoAnnotationBucket = storageClient.bucket(config.video_json_bucket);
const videoAnnotationFilename = (file.metadata.name).replace('/', '').replace('.', '') + '.json';
const annotationFile = videoAnnotationBucket.file(videoAnnotationFilename);
// GET ANNONATIONS FOR EACH FILE
annotationFile.get(function(error, fileData) {
if (error) {
console.log('error getting file', error);
}
else {
const remoteJsonUrl = fileData.metadata.mediaLink;
// console.log(fileData.metadata);
request({
url: remoteJsonUrl,
json: true
},
function(jsonReadErr, jsonResp, body) {
console.log('logging body:');
console.log(body);
The error is occuring on the callback, and I'm reading the error via console.log(body) which gives me the error message I stated above.
What's weird is it's saying I'm anonymous when I did gcloud auth login as well as I'm providing creds when I declare storageBucket as such:
const storageClient = storage({
credentials: {
"client_email": "clientEmail",
"private_key": "privateKey",
},
projectId: "projectId"
});
So right off the bar, to avoid any "did you set this" questions, no I am not actually supplying those values I omitted the real values, and we use them elsewhere so I know they are correct.
My question is, what does Anonymous caller mean? And how can I fix it? How is it thinking I am anonymous when I did all the (seemingly) necessary things to use the API?
It's possible that you need to explicitly authenticate within request. This SO thread looks related.
Let us know how explicitly authenticating worked out!
I am in the process of building my first Node app, and I am having troubles with unirest.get requests. My project is built using Node, Express, Node and the Act On API.
I am using the express generator to get the project of the ground quickly.
The problem I am experiencing is that I am struggling to get the response through to my route file. I am requesting a list from the Act On API which is returning correctly as I can see the response in the console when I log it, but cannot get the data through to the templates.
function getTheList(callback) {
var Request = unirest.get('https://restapi.actonsoftware.com/api/1/list/l-0001')
.headers({
'Accept': 'application/json',
'Authorization': 'Bearer ' + access_token
})
.query({
"count": 20,
"fields": "First Name;Last Name;Email;"
})
.end(function(response, error) {
var data = response.body.data;
if (!error && response.statusCode == 200) {
callback(returnData(data));
} else {
console.log('Failed response');
}
});
}
function returnData(theData){
console.log(theData);
return theData;
}
module.exports.get = getTheList;
And the code inside my routes file to get this information.
var masterList = require('../acton/getMasterList');
var myListVar = masterList.get();
Any help on what I am doing wrong would be greatly appreciated.
The getTheList function that you describe expects a callback which you don't provide when you call it like so masterList.get().
So you can either do something like:
masterList.get(function(data){
//you can access data here.
})
Or, in the getTheList implementation just do away with the callback entirely.
.end(function(response, error) {
var data = response.body.data;
if (!error && response.statusCode == 200) {
returnData(data); //Just do this may be.
} else {
console.log('Failed response');
}
});