I'm using NodeJS, Express and GoogleApis en Google-oauth-jwt to authenticate.
I'm having problems with getting data from my second promise function (getData).
I can succesfully retrieve a token, when I use res.json(myToken) in the getToken().then(function(myToken). However I'm having problems using this token in the getData(token) function.
When I'm finally able to retrieve data from the googleapis via the getData function,I'd like to save this data into a MongoDB, to reduce calls to the Google Analytics API.
These are the errors I get:
2018-01-11T09:46:55.063Z 5ac2c6f1-f6b4-11e7-a2e2-c50e9f880e28 token: XXXXXXXXXXXXXXX
2018-01-11T09:46:55.148Z 5ac2c6f1-f6b4-11e7-a2e2-c50e9f880e28 { Error:
Login Required at RequestError.Error (native) at new RequestError
(/var/task/node_modules/google-auth-library/lib/transporters.js:34:42)
at Request._callback
(/var/task/node_modules/google-auth-library/lib/transporters.js:96:27)
at Request.self.callback
(/var/task/node_modules/request/request.js:186:22) at emitTwo
(events.js:106:13) at Request.emit (events.js:191:7) at
Request.
(/var/task/node_modules/request/request.js:1163:10) at emitOne
(events.js:96:13) at Request.emit (events.js:188:7) at
IncomingMessage.
(/var/task/node_modules/request/request.js:1085:12) code: 401, errors:
[ { domain: 'global', reason: 'required', message: 'Login Required',
locationType: 'header', location: 'Authorization' } ] }
2018-01-11T09:46:55.153Z 5ac2c6f1-f6b4-11e7-a2e2-c50e9f880e28 (node:1) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Login Required
This is my code:
var express = require('express');
var router = express.Router();
var googleAuth = require('google-oauth-jwt');
var google = require('googleapis');
var app = express();
/* get GA data*/
router.get('/kpis', function(req, res, next) {
// get token with googleapis library
function getToken() {
return new Promise(function(resolve,reject) {
googleAuth.authenticate({
email: 'serviceAcountemail#email.com',
key: "getting key",
scopes: ['https://www.googleapis.com/auth/analytics.readonly']
}, function (err, token) {
if (err){
reject(err)
} else
resolve(token)
});
});
}
function getData(token){
return new Promise(function(resolve,reject){
var analytics = google.analytics('v3');
var VIEW_ID = 'ga:profileid';
analytics.data.ga.get({
'auth': token,
'ids': VIEW_ID,
'metrics': 'ga:uniquePageviews',
'dimensions': 'ga:pagePath',
'start-date': '30daysAgo',
'end-date': 'yesterday',
'sort': '-ga:uniquePageviews',
'max-results': 10,
}, function (err, response) {
if (err) {
console.log(err)
reject(err)
} else
console.log('Response:',response)
resolve(response)
});
});
}
getToken().then(function(myToken) {
// get the token, make a call to google analytics api with token included in auth
console.log('token:', myToken);
getData(myToken).then(function(results){
// show results on screen in json
res.json(gaResults);
});
});
});
/* end of get GA data*/
module.exports = router;
My question:
Related
Really struggling to get my head around authO management clients so I can update users information. I've created a Next.js API route for the backend but I'm not sure how to actually amend the user's data. I've followed the docs and got to the point below.
API route
The ID params I manually entered to test and my response is an empty JSON object.
The docs don't make it clear what I'm suppose to do in the update user area in.
var ManagementClient = require("auth0").ManagementClient;
export default async (req, res) => {
var auth0 = new ManagementClient({
domain: process.env.AUTH0_BASE_URL,
clientId: process.env.AUTH0_CLIENT_ID,
clientSecret: process.env.AUTH0_CLIENT_SECRET,
scope: "read:users update:users",
});
var params = { id: "**************************" };
var metadata = {
foo: "bar",
};
auth0.users.updateAppMetadata(params, metadata, function (err, user) {
if (err) {
// Handle error.
}
// Updated user.
console.log(user);
res.status(200).json({ user });
});
};
Error:
API resolved without sending a response for /api/authapi, this may result in stalled requests.
SanitizedError [APIError]: getaddrinfo ENOTFOUND http
(node:internal/process/task_queues:81:21) {
statusCode: 'ENOTFOUND',
requestInfo: { method: 'post', url: '***********' },
originalError: Error: getaddrinfo ENOTFOUND http
at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:69:26) {
errno: -3008,
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'http',
response: undefined
}
}
I'm running into a strange problem with AWS Cognito. I'm able to create user accounts, however when I attempt to set the created user to a group it is
giving me a network timed out error.
Setup:
const AmazonCognitoIdentity = require('amazon-cognito-identity-js')
const AWS = require('aws-sdk')
const CognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider({
region: 'us-east-1 ', // 100% sure this is the correct region
apiVersion: '2016-04-18'
})
const UserPoolId = config.cognito.userPoolId
const ClientId = config.cognito.clientId
const userPool = new AmazonCognitoIdentity.CognitoUserPool({ UserPoolId, ClientId })
Creating account:
userPool.signUp(email, password, [ emailAttribute ], null, (err, data) => {
if(err) {
console.error(err)
return res.redirect('/signup')
}
CognitoIdentityServiceProvider.adminAddUserToGroup({
GroupName: 'TRIAL',
UserPoolId,
Username: email
}, (err, data) => {
if(err) {
console.error(err)
return res.redirect('/signup')
}
res.redirect('/dashboard')
})
})
The account gets made correctly, however when attempting to add the new account to a group I get this error:
{ Error: connect ETIMEDOUT 104.239.207.44:443
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1198:14)
message: 'connect ETIMEDOUT 104.239.207.44:443',
code: 'NetworkingError',
errno: 'ETIMEDOUT',
syscall: 'connect',
address: '104.239.207.44',
port: 443,
region: 'us-east-1 ',
hostname: 'cognito-idp.us-east-1',
retryable: true,
time: 2018-06-20T14:01:49.029Z }
I find this very strange as I just was able to create an account successfully.
Any ideas on why this is happening?
Thanks
I'm trying to call freecodecamp api #url https://forum.freecodecamp.org/c/getting-a-developer-job.json?
I am doing some analysis on the data, but when I call this service using 'request' npm package I am getting ssl error as follows:
error { Error: write EPROTO 140735782093632:error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:../deps/openssl/openssl/ssl/s3_pkt.c:1500:SSL alert number 40
140735782093632:error:1409E0E5:SSL routines:ssl3_write_bytes:ssl handshake failure:../deps/openssl/openssl/ssl/s3_pkt.c:659:
at _errnoException (util.js:1022:11)
at WriteWrap.afterWrite [as oncomplete] (net.js:867:14) code: 'EPROTO', errno: 'EPROTO', syscall: 'write' }
Can somebody let me know what the issue is? A wget call pulls the data when provided with --ca-certificate option, also the webservice is giving data to postman without any certificate.
Here is my code:
import request from 'request';
import fs from 'fs';
const BASE_URL = 'forum.freecodecamp.org/c/getting-a-developer-job.json?no_subcategories=false&page=1';
request.get(BASE_URL, {
port: 443,
agentOptions: {
ciphers: 'ALL',
ca: fs.readFileSync('./mycertfile.pem'),
secureProtocol: 'TLSv1_2_method'
},
strictSSL: false
})
.on('response', (response) => {
console.log('Response is ', response);
}).on('error', (err) => {
console.log('error', err);
});
I see no problems there except URI http:// is absent, in my environment i have node v10.5.0, and the slightly modified version of your script works well:
const request = require('request')
const BASE_URL = 'https://forum.freecodecamp.org/c/getting-a-developer-job.json?no_subcategories=false&page=1'
request.get(BASE_URL, { json: true }, (err, res, body) => {
if (err) throw('error', err);
console.log('JSON object is => ', body);
})
outputs to console:
JSON object is => { users:
[ { id: 117390,
username: 'anthony2025',
....
This is my server.js. When I run node server.js then use PostMan to post json, it gives me the following error.
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
app.use(bodyParser.json())
app.get('/api/posts', function(req, res) {
res.json([
{
username: '#rodandrew95',
body: 'node rocks!'
}
])
})
app.listen(3000, function() {
console.log('Server listening on', 3000)
})
var Post = require('./models/post')
app.post('/api/posts', function(req, res, next) {
// console.log('post received')
// console.log(req.body.username)
// console.log(req.body.body)
// res.sendStatus(201)
var post = new Post({
username: req.body.username,
body: req.body.body
});
post.save(function (err, post) {
if (err) { return next(err) }
res.sendStatus(201).json(post)
})
})
The error:
(node:6863) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
ValidationError: Post validation failed
at MongooseError.ValidationError (/Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/error/validation.js:23:11)
at model.Document.invalidate (/Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/document.js:1486:32)
at /Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/document.js:1362:17
at validate (/Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/schematype.js:705:7)
at /Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/schematype.js:742:9
at Array.forEach (native)
at SchemaString.SchemaType.doValidate (/Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/schematype.js:710:19)
at /Users/andrewrodrigues/Desktop/write_modern/ch_1/node_modules/mongoose/lib/document.js:1360:9
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
I'm trying to learn the MEAN stack through "Write Modern Web Apps with the MEAN Stack" but I'm running into issues all the time, even when I follow the code and instructions exactly. Can anyone help understand this error, and possibly recommend some good resources for learning the mean stack?
This error is triggered because you have provided a mongoose validation in
your schema (in /models/post) and that validation is failing.
For instance, if you provided your model like this :
var postSchema = new Schema({
"username": String,
"body": String,
"email": {
type: String,
required: true
}
});
var Post = mongoose.model('Post', postSchema);
This would fail because email required validator is not respected. Find a full list of validators here.
Side note : res.sendStatus(201).json(post) will set the json body and content-type header after sending a response with 201 status. To send both use :
res.status(201).json(post)
My Code follows,(above code is same as given in the example of nodejs in google developer site.)
function listLabels(auth) {
var gmail = google.gmail({ auth: auth, version: 'v1' });
var emails = gmail.users.messages.list({
includeSpamTrash: false,
maxResults: 500,
q: "",
userId: 'me'
}, function (err, results) {
console.log(results.messages);
});
}
I'm getting array of objects containing IDs and threadIds
Now, if i input these IDs
into these
function getMessage(messageId,auth) {
var requestt = google.gmail({ auth: auth, version: 'v1' }).users.messages.get({
'userId': 'me',
'id': messageId
});
console.log(requestt)
requestt.execute(function(response){
console.log(response);
});
}
I am getting error,
TypeError: requestt.execute is not a function
at getMessage (/home/jay/Projects/gmailwebapi/index.js:122:11)
at /home/jay/Projects/gmailwebapi/index.js:113:7
at OAuth2Client._postRequest (/home/jay/Projects/gmailwebapi/node_modules/google-auth-library/lib/auth/oauth2client.js:381:3)
at postRequestCb (/home/jay/Projects/gmailwebapi/node_modules/google-auth-library/lib/auth/oauth2client.js:343:10)
at Request._callback (/home/jay/Projects/gmailwebapi/node_modules/google-auth-library/lib/transporters.js:103:7)
at Request.self.callback (/home/jay/Projects/gmailwebapi/node_modules/google-auth-library/node_modules/request/request.js:198:22)
at emitTwo (events.js:100:13)
at Request.emit (events.js:185:7)
at Request.<anonymous> (/home/jay/Projects/gmailwebapi/node_modules/google-auth-library/node_modules/request/request.js:1057:14)
at emitOne (events.js:95:20)
You could use the callback the same way you do when you list messages:
function getMessage(messageId, auth) {
var gmail = google.gmail({ auth: auth, version: 'v1' });
gmail.users.messages.get({
'userId': 'me',
'id': messageId
}, function (err, result) {
console.log(result);
});
}