I don't understand why my code only works on debug mode. my variable musiques in my function createMusicBox() is an object in debug mode and null in not debuging
var musiques = [];
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Lists the names and IDs of up to 10 files.
*
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function listFiles(auth) {
var service = google.drive('v3');
service.files.list({
auth: auth,
pageSize: 10,
fields: "nextPageToken, files(id, name)"
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var files = response.files;
if (files.length == 0) {
console.log('No files found.');
} else {
musiques=files;
console.log('Files:');
for (var i = 0; i < files.length; i++) {
musiques[i] = files[i];
var file = files[i];
console.log('%s (%s)', file.name, file.id);
}
}
});
}
// this function pulls music in my google drive
function createMusicBox() {
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the Drive API.
authorize(JSON.parse(content), listFiles);
});
console.log(musiques);
}
I find a solution, i put a callback in listFiles and now it works perfectly
function createMusicBox(event) {
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the Drive API.
authorize(JSON.parse(content), listFiles, event);
});
}
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
function listFiles(auth, callback, event) {
var service = google.drive('v3');
service.files.list({
auth: auth,
pageSize: 10,
fields: "nextPageToken, files(id, name)"
}, function(err, response, listMusic) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var files = response.files;
if (files.length == 0) {
console.log('No files found.');
} else {
callback(event, files);
}
});
}
Related
Have a Node webserver(webserver.js) which serves file to clients browser. This webserver uses my file and api require("google-calendar.js");.
What is best practise to serve the google calendar result from Node to the webbrowser?
The webbserver wants to send pages syncronized but the google-api runs asynchronized which currently means result is showing up once the page is reloaded.
Below is the current code for doing this. All kind of feedback is appreciated.
www/index.html:
<html>
<head>
</head>
<body>
<iframe type="text/html" src="calendar.html"></iframe>
</body>
</html>
www/calendar.html:
CONTENT GENERATED BY webserver.js
webserver.js:
var port = 9800;
var serverUrl = "127.0.0.1";
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var http = require("http");
var path = require("path");
var fs = require("fs");
var url = require('url');
var checkMimeType = false;
var calendar = require('./google-calendar');
console.log("Starting web server at " + serverUrl + ":" + port);
var calPage = "";
function setCalendarPage(content) {
calPage = content;
console.log("Setting calendar content: " + calPage);
}
http.createServer(function(req, res) {
calendar.getEvents(setCalendarPage);
var request = req;
var filename = req.url;
console.log("====================");
console.log(filename);
if (filename == '/') {
filename = "/index.html";
}
sendFile(filename, res);
}).listen(port, serverUrl);
function getMimeType(filename) {
var ext = path.extname(filename);
var validExtensions = {
".html": "text/html",
".js": "application/javascript",
".css": "text/css",
".txt": "text/plain",
".jpg": "image/jpeg",
".gif": "image/gif",
".png": "image/png",
".woff": "application/font-woff",
".woff2": "application/font-woff2"
};
return validExtensions[ext];
}
function sendFile(filename, res) {
var localPath = __dirname;
localPath += ("/www" + filename);
fs.exists(localPath, function(exists) {
if (exists) {
let mimeType = getMimeType(filename);
getFile(localPath, res, mimeType);
} else {
console.log("File not found: " + localPath);
res.writeHead(404);
res.end();
}
});
}
function getFile(localPath, res, mimeType) {
fs.readFile(localPath, function(err, contents) {
if (!err) {
if (mimeType != undefined) {
res.setHeader("Content-Type", mimeType);
}
res.statusCode = 200;
if (localPath.includes("calendar")) {
var calContent = getHtmlPage(calPage);
res.setHeader("Content-Length", calContent.length);
res.end(calContent);
} else {
res.setHeader("Content-Length", contents.length);
res.end(contents);
}
} else {
res.writeHead(500);
res.end();
}
});
function getHtmlPage(text) {
var html = '<html><head>';
html += '<meta charset="UTF-8">';
html += '<title></title>';
html += '</head>';
html += '<body>';
html += text;
html += '</body>';
html += '</html>';
return html;
}
}
google-calendar.js:
const fs = require('fs');
const mkdirp = require('mkdirp');
const readline = require('readline');
const {google} = require('googleapis');
const OAuth2Client = google.auth.OAuth2;
const SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'];
const TOKEN_PATH = 'credentials.json';
var result = "";
// Load client secrets from a local file.
module.exports = {
getEvents : function (callback){
if(result != ""){
return;
}
fs.readFile('client_secret.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Drive API.
return authorize(JSON.parse(content),callback);
});
}
};
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials,callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new OAuth2Client(client_id, client_secret, redirect_uris[0]);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getAccessToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
return listEvents(oAuth2Client, callback);
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* #param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback for the authorized client.
*/
function getAccessToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return callback(err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
/**
* Lists the next 10 events on the user's primary calendar.
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function listEvents(auth, callback) {
result = "";
const calendar = google.calendar({version: 'v3', auth});
calendar.events.list({
calendarId: 'primary',
timeMin: (new Date()).toISOString(),
maxResults: 10,
singleEvents: true,
orderBy: 'startTime',
}, (err, {data}) => {
if (err) return console.log('The API returned an error: ' + err);
const events = data.items;
if (events.length) {
console.log('Upcoming 10 events:');
events.map((event, i) => {
const start = event.start.dateTime || event.start.date;
console.log(`${start} - ${event.summary}`);
result += `${start} - ${event.summary} <br>`;
});
callback(result);
} else {
console.log('No upcoming events found.');
}
});
}
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/youtube-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json';
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the YouTube API.
authorize(JSON.parse(content), getChannel);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function (err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* #param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function (code) {
rl.close();
oauth2Client.getToken(code, function (err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* #param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
/**
* Lists the names and IDs of up to 10 files.
*
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function getChannel(auth) {
var service = google.youtube('v3');
service.channels.list({
auth: auth,
part: 'snippet,contentDetails,statistics',
forUsername: 'GoogleDevelopers'
}, function (err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var channels = response.items;
if (channels.length == 0) {
console.log('No channel found.');
} else {
console.log('This channel\'s ID is %s. Its title is \'%s\', and ' +
'it has %s views.',
channels[0].id,
channels[0].snippet.title,
channels[0].statistics.viewCount);
}
});
}
I copied the code from youtube's data API tutorial for node.js
https://developers.google.com/youtube/v3/quickstart/nodejs
I entered the password from the link in the first time.
and now when I run the application I get this output:
The API returned an error: Error: Required parameter: part
this is part
part: 'snippet,contentDetails,statistics',
I guess this is not what you are asking for, but reverting back to version 24.0.0 worked for me:
excerpt from my packages.json
...
"googleapis": "24.0.0",
...
const express = require('express'),
bodyParser = require('body-parser'),
Sequelize = require('sequelize')
const app=express()
app.use(bodyParser.json())
var google = require('googleapis');
var contacts = google.people('v1');
const nconf = require('nconf');
const readline = require('readline');
const plus = google.plus('v1');
const path = require('path');
const OAuth2Client = google.auth.OAuth2;
nconf.argv().env().file(path.join(__dirname, '/oauth2.keys.json'));
const keys = nconf.get('web');
const CLIENT_ID = '1058912681476-uat19si2uli37vlehs2avqfue2l0b6ku.apps.googleusercontent.com';
const CLIENT_SECRET = 'PbY8AVICTQsywb4qiqCJ8gMB';
const REDIRECT_URL = 'urn:ietf:wg:oauth:2.0:oob';
const oauth2Client = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function getAccessToken (oauth2Client, callback) {
// generate consent page url
const url = oauth2Client.generateAuthUrl({
access_type: 'offline', // will return a refresh token
scope: 'https://www.googleapis.com/auth/plus.me' // can be a space-delimited string or an array of scopes
});
console.log('Visit the url: ', url);
rl.question('Enter the code here:', code => {
// request access token
oauth2Client.getToken(code, (err, tokens) => {
if (err) {
return callback(err);
}
// set tokens to the client
// TODO: tokens should be set by OAuth2 client.
oauth2Client.credentials=tokens;
callback();
});
});
}
// retrieve an access token
getAccessToken(oauth2Client, () => {
// retrieve user profile
plus.people.get({ userId: 'me', auth: oauth2Client }, (err, profile) => {
if (err) {
throw err;
}
console.log(profile.displayName, ':', profile.tagline);
});
});
//here-not working
contacts.people.connections.list({
auth: oauth2Client //authetication object generated in step-3
}, function (err, response) {
// handle err and response
if(err){
throw err;
}
console.log(response.names);
});
app.listen(8080)
I'm trying to get the contacts of an user from the google people api(https://developers.google.com/people/api/rest/v1/people.connections/list) but when I try to call contacts.people.connection.list() I get Error:
Missing required parameters: resourceName
at Object.createAPIRequest (/home/ubuntu/workspace/contactmanager/backend/node_modules/googleapis/build/src/lib/apirequest.js:94:18);
The error says it all. The resourceName is a required parameter. If you look in the people.connections.list you must provide a 'people/me' value as parameter. Other values are invalid.
GET https://people.googleapis.com/v1/{resourceName=people/me}/connections
#noogui already answered the reason . Here is the more elaborative code for the use case:
function listConnectionNames(auth) {
const service = google.people({
version: "v1",
auth
});
service.people.connections.list({
resourceName: "people/me",
pageSize: 10,
personFields: "names,emailAddresses"
},
(err, res) => {
if (err) return console.error("The API returned an error: " + err);
const connections = res.data.connections;
if (connections) {
console.log("Connections:");
connections.forEach(person => {
if (person.names && person.names.length > 0) {
console.log(person.names[0].displayName);
} else {
console.log("No display name found for connection.");
}
});
} else {
console.log("No connections found.");
}
}
);
}
So basically what I've done here is I've hijacked the google sheets api node.js quickstart guide for my own purposes. Everything in here works great up until it hits my spreadsheets.batchUpdate and then everything gets wacky.
If I comment out the "auth" initialization in spreadsheets.batchUpdate I get the error message: The API returned an error: Error: The request does not have valid authentication credentials.
If I comment out the "auth" initialization in spreadsheets.batchUpdate I get the error message: The API returned an error: Error: Request had insufficient authentication scopes.
All I'm trying to do with these calls is get some data out of the sheet and then delete the rows after but I can't figure out this authentication issue.
var fs = require('fs');
var updateDB = require('./updateDB.js');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var splitData;
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'sheets.googleapis.com-nodejs-quickstart.json';
var array = [];
var run = {
runQuickstart : function() {
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the
// Google Sheets API.
authorize(JSON.parse(content), listMajors);
});
}
}
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* #param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* #param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
/**
* Print the names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
function listMajors(auth) {
var sheets = google.sheets('v4');
sheets.spreadsheets.values.get({
auth: auth,
spreadsheetId: '1EV8S8AaAmxF3vP0F6RWxKIUlvF6uFEmsrOFWA1oNBYI',
range: 'Form Responses 1!A3:X3',
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var rows = response.values;
//splitData = rows.split(',');
updateDB.inputFormToDB.apply(this, rows);
if (rows.length == 0) {
console.log('No data found.');
} else {
console.log('Form Responses');
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
// Print columns A and E, which correspond to indices 0 and 4.
console.log('%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s', row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9],row[10], row[11], row[12], row[13], row[14], row[15], row[16], row[17], row[18], row[19], row[20], row[21], row[22], row[23]);
}
var spreadsheetId = '1EV8S8AaAmxF3vP0F6RWxKIUlvF6uFEmsrOFWA1oNBYI';
var requests = [];
requests.push({
"deleteDimension": {
"range": {
"sheetId": spreadsheetId,
"dimension": "ROWS",
"startIndex": 0,
"endIndex": 3
}
}
});
var batchUpdateRequest = {requests: requests}
var test = auth;
sheets.spreadsheets.batchUpdate({
// auth: test,
spreadsheetId: spreadsheetId,
resource: batchUpdateRequest
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
});
}
});
}
module.exports = run;
https://www.googleapis.com/auth/spreadsheets.readonly will give you read rights.
You need to use the https://www.googleapis.com/auth/spreadsheets scope to update the sheet.
https://www.googleapis.com/auth/spreadsheets.readonly
Allows read-only access to the user's sheets and their properties.
https://www.googleapis.com/auth/spreadsheets
Allows read/write access to the user's sheets and their properties.
I'm using nodejs, express 4 and everyauth for social network authentication. I'm having some problem where I click Accept from Google and and redirects back to my / I get
_http_outgoing.js:335
throw new Error('Can\'t set headers after they are sent.');
I'm using electrolyte as a DI as well but I don't think that would be an issue. Here's my code
index.js
var express = require('express'),
http = require('http'),
bootable = require('bootable');
var app = bootable(express());
app.phase(bootable.initializers('etc/init', app));
app.phase(bootable.routes(__dirname + '/routes.js', app));
app.phase(function listen(done) {
http.createServer(app).listen(process.env.PORT || 3000, function(err) {
if (err) { return done(err); }
var addr = this.address();
console.log('server listening on http://' + addr.address + ':' + addr.port);
done();
});
});
module.exports = app;
routes.js
var IoC = require('electrolyte');
module.exports = function routes() {
this.get('/', IoC.create('handlers/homepage'));
this.get('/api/foursquare', IoC.create('handlers/api/foursquare'));
//this.get('/auth/google/callback', IoC.create('handlers/auth/google_auth_callback'));
}
handlers/homepage
exports = module.exports = function() {
function render(req, res, next) {
res.render('index');
};
return [render];
};
google.js
var everyauth = require('everyauth'),
GoogleUser = require('../../app/models/google_user'),
mongoose = require('../../app/db/mongo');
require('dotenv').load();
module.exports = function() {
everyauth.google
.appId(process.env.GOOGLE_CLIENT_ID)
.appSecret(process.env.GOOGLE_CLIENT_SECRET)
.scope('https://www.googleapis.com/auth/plus.login') // What you want access to
.handleAuthCallbackError( function (req, res) {
// If a user denies your app, Google will redirect the user to
// /auth/facebook/callback?error=access_denied
// This configurable route handler defines how you want to respond to
// that.
// If you do not configure this, everyauth renders a default fallback
// view notifying the user that their authentication failed and why.
})
.findOrCreateUser( function (session, accessToken, accessTokenExtra, googleUserMetadata) {
console.log('come back from google');
console.log(session);
// find or create user logic goes here
// Return a user or Promise that promises a user
// Promises are created via
// var promise = this.Promise();
/*
var googleUser = new GoogleUser(mongoose);
var johndoe = new googleUser({
accessToken: 'accessToken',
expires: new Date(),
refreshToken: 'refreshToken',
email: 'john#doe.com',
createdAt: new Date()
});
var promise = this.Promise();
promise.resolve(johndoe);
return promise;
*/
}).redirectPath('/');
};
mongo.js
var mongoose = require('mongoose')
require('dotenv').load();
var uristring = process.env.MONGOLAB_URI;
mongoose.connect(uristring, function (err, res) {
if (err) {
console.log ('ERROR connecting to: ' + uristring + '. ' + err);
} else {
console.log ('Succeeded connected to: ' + uristring);
}
});
exports = module.exports = mongoose
You will get Can't set headers after they are sent. if your code is like this
if (err) {
res.send(err);
}
else if(!user) {
res.send(info);
}
res.send(user);
In the above code, if user is undefined it sends the info as response and it again comes to next statement i.e res.send(user);. So it cannot set headers to the response which is already sent.
You can prevent this by
if (err) {
res.send(err);
}
else if(!user) {
res.send(info);
}
else {
res.send(user);
}
or
if (err) {
return res.send(err);
}
else if(!user) {
return res.send(info);
}
return res.send(user);