Node.js

278

Solutions

373

Contributors

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

Share tech news, updates, or what's on your mind.

Sign up to Post

Hi Experts,

I have a Microsoft Failover Cluster with 2 nodes and a Quorum disk (file share witness). Lately when I've taken one node offline for maintenance the cluster has shutdown all my VM's, I've had to reconnect to the cluster and then my VM's restart and come online. I always test the FSW before I take a node server offline and it always responds. Right now I can no longer trust the cluster. Below are the 2 events recorded...

Critical

File share witness resource 'File Share Witness' failed to arbitrate for the file share '\\<SERVERNAME>\WitnessCluster2'. Please ensure that file share '\\<SERVERNAME>\WitnessCluster2' exists and is accessible by the cluster.

Error

Cluster resource 'File Share Witness' of type 'File Share Witness' in clustered role 'Cluster Group' failed.

Based on the failure policies for the resource and role, the cluster service may try to bring the resource online on this node or move the group to another node of the cluster and then restart it.  Check the resource and group state using Failover Cluster Manager or the Get-ClusterResource Windows PowerShell cmdlet.


How do I stop this happening on my cluster, it does not make sense because the FSW is available and online but as soon as I restart a host node my cluster falls apart and its a real problem when you have 20 VM's that depend on it working.

The 2 nodes are running with Windows Server 2012 R2 Datacenter
The FSW is located on a server running …
0
Angular Fundamentals
LVL 20
Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

This is my "is-auth.js" file:

const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
	//console.log(req.get(Authorization));
	const authHeader = req.get('Authorization');
	if(!authHeader) {
		const error = new Error('Not Even Working');
		error.statusCode = 401;
		throw error;
	} else {
		const token = authHeader.split(' ')[1];
		let decodedToken;
		try {
			decodedToken = jwt.verify(token, 'secret');
		} catch (err) {
			err.statusCode = 500;
			throw err;
		}
		if(!decodedToken) {
			const error = new Error('Not Authenticated');
			error.statuscode = 401;
			throw error;
		}
		req.userID = decodedToken.userId;
		next();
	}
};

Open in new window


If you notice the line, "//console.log(req.get(Authorization));," - if I un-commented that line, I would get an error that said, "message: "Authorization is not defined."

I'm thinking that's because the "console.log..." thing can't be referenced in the code the way that I have it. And what makes it hard to "see," is that unless you're aware of how a method needs to be crafted and WHERE you can actually do a "console.log," you're going to beat your head up against the way looking for another error.

Am I correct?

Is the placement of "console.log(req.get(Authorization))" toxic? Is that a dealbreaker? Will that break the code?

And what's a good rule of thumb for "console.log" as far as where you can put it within a method and not be writing code that's going to break however sound it might otherwise be?
0
Here's the code:

exports.createPost = (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    const error = new Error("Validation failed, entered data is incorrect.");
    error.statusCode = 422;
    throw error;
  }
  if (!req.file) {
    const error = new Error("No image provided");
    errorStatusCode = 422;
    throw error;
  }
  const imageUrl = req.file.path.replace("\\", "/");
  const title = req.body.title;
  const content = req.body.content;
  const post = new Post({
    title: title,
    content: content,
    imageUrl: imageUrl,
    creator: req.userId
  });
  post
    .save()
    .then(result => {
	  return User.findById(req.userId);
	})
      res.status(201).json({
        message: "Post created successfully",
        post: result
      });
    })
    .catch(err => {
      if (!err.statusCode) {
        err.statusCode = 500;
      }
      next(err);
    });
};

Open in new window


This is a working piece of code that belongs to a Node.js tutorial that I'm going through.

Not wanting to just "cut and paste," I found myself wondering about "return."

I've been operating under the impression that anytime you use "return," you're putting the breaks on within your functionality and nothing else fires beyond that point.

I'm getting that from definitions such as this:

The return statement stops the execution of a function and returns a value from that function.
( https://www.w3schools.com/jsref/jsref_return.asp)

I'm savvy enough to appreciate the utility of what's happening above in that I'm running the "User.findById(req.userID)" query, but the fact that the result is being "returned" made me want to run this past some greater minds that my own and get some clarification on what "return" means in this instance in that it's obviously not compelling the remainder of the code to cease.

Is there a more comprehensive definition of "return" that makes the way in which it's used in this context make sense?
0
We've been asked to download a project and be ready to comment intelligently in a meeting tomorrow, so I'm trying to get this app up and running on my local box, but I'm running into errors that I've not encountered before.

Here is the error as it appears on my terminal:

Listening on PORT: 3000
(node:3316) UnhandledPromiseRejectionWarning: MongoError: not authorized on test to execute command { insert: "system.indexes", documents: [ { ns: "test.user_sess
ions", key: { expires: 1 }, name: "expires_1", expireAfterSeconds: 0, unique: false } ], ordered: true, writeConcern: { w: "majority" }, lsid: { id: UUID("9674b2b
b-4da6-401a-9d90-7b0f35ace911") }, readConcern: { afterClusterTime: Timestamp(1579010568, 1) }, $clusterTime: { clusterTime: Timestamp(1579010568, 1), signature:
{ hash: BinData(0, 2F281F7B9881E802501648F77CC4113E4B119167), keyId: 6749132984986632193 } }, $db: "test" }
    at Connection.<anonymous> (C:\wamp64\www\bsmart\PRAMS\node_modules\mongoose\node_modules\mongodb-core\lib\connection\pool.js:443:61)
    at Connection.emit (events.js:210:5)
    at processMessage (C:\wamp64\www\bsmart\PRAMS\node_modules\mongoose\node_modules\mongodb-core\lib\connection\connection.js:364:10)
    at TLSSocket.<anonymous> (C:\wamp64\www\bsmart\PRAMS\node_modules\mongoose\node_modules\mongodb-core\lib\connection\connection.js:533:15)
    at TLSSocket.emit (events.js:210:5)
    at addChunk (_stream_readable.js:309:12)
    at readableAddChunk (_stream_readable.js:290:11)
  

Open in new window

0
Here's my code:

module.exports = (req, res, next) => {
	const authHeader = req.get('Authorization');
	if(!authHeader) {
		const error = new Error('Not Even Working');
		error.statusCode = 401;
		throw error;
	} else {
		//const token = authHeader.split(' ')[1];
		let decodedToken;
		try {
			decodedToken = jwt.verify(token, 'secret');
		} catch (err) {
			err.statusCode = 500;
			throw err;
		}
		if(!decodedToken) {
			const error = new Error('Not Authenticated');
			error.statuscode = 401;
			throw error;
		}
		req.userID = decodedToken.userId;
		next();
	}
};

Open in new window


I'm going through some of my back end and forcibly making things go south and I've discovered that I like being able to see things like "Not Even Working," in addition to my status code.

Now, all cards on the table, the above code is coming from a tutorial, so I'm not all that, but I still want to ask this question:

In the first block, I establish an "error" const and I throw my error which has some verbiage that helps me know exactly where things went south.

The next block I've got a try / catch.

Now, when I think "try / catch," I'm thinking this is just a different kind of IF clause, yes? Perhaps the "try" presupposes the fact that we're actually going to fire some kind of function as opposed to just testing the presence of a variable?

But I want to have something even in the context of a "try / catch," where I can specify a "new Error," so I can write some custom verbiage to my console.

So, why am I using "try / catch?" I understand the utility of "throw," because that prevents the code from moving forward.

But why "try / catch? as opposed to a regular IF and can I incorporate some custom verbiage in the midst of that "try / catch?"

Thanks!
0
New to Node.js, but getting more comfortable with it every day.

Ah, but wait...

We got a note today from the boss that we need to head out to a repository, download the codebase and start looking it over.

So I clone the repository and this is what I have on my local box:

prams
I'm assuming that "PRAMS" is kind of like a suitcase for a Node.js application based on what I see here: https://www.npmjs.com/package/pram

...but I would like some confirmation on that.

Next, I follow my nose and I copy and paste the contents of the PRAMS directory to that place where I can fire it up on my local box.

But what port is it going to be firing on?

I run npm index.us and I get this:

Usage: npm <command>

where <command> is one of:
    access, adduser, audit, bin, bugs, c, cache, ci, cit,
    clean-install, clean-install-test, completion, config,
    create, ddp, dedupe, deprecate, dist-tag, docs, doctor,
    edit, explore, get, help, help-search, hook, i, init,
    install, install-ci-test, install-test, it, link, list, ln,
    login, logout, ls, org, outdated, owner, pack, ping, prefix,
    profile, prune, publish, rb, rebuild, repo, restart, root,
    run, run-script, s, se, search, set, shrinkwrap, star,
    stars, start, stop, t, team, test, token, tst, un,
    uninstall, unpublish, unstar, up, update, v, version, view,
    whoami

npm <command> -h  quick help on <command>
npm -l            display full usage info
npm help <term>   

Open in new window

0
I have a node.js app and am developing a separate single page app (that will eventually be converted into Android and iOS native apps). I'm setting up an API on the node.js app and am struggling with authentication. The node.js app is using passport-local for authentication and I store user data in a MongoDB backend.

So far, I have a GET and POST routes that look like this:
router.get('/api/devices', catchErrors(deviceController.getDevicesAPI));
router.post('/api/devices', authController.isAuthorized, catchErrors(deviceController.getDevicesAPI));

Open in new window


My remote authentication request looks like this:
const axios = require('axios');
const url = 'http://localhost:7777/api/devices';
const user = {
  username,
  password,
};

function authenticate() {
  axios
    .post(url, user)
    .then(function(response) {
      console.log('Authenticated ', response);
    })
    .catch(function(error) {
      console.log('Error on Authentication ', error);
    });
}

Open in new window


My question is how can I take the username/password in the HTTP request to authenticate against an existing user in the node.js app? I was hoping I could just pass the values to passport-local, something like :

exports.isAuthorized = (req, res, next) => {
  const username = req.body.username;
  const password = req.body.password;
  passport.authenticate('local', function(err, user, info) {
    
    console.log(req.body);
    if (err) { return next(err); }
    next();
  })(req, res, next);
};

Open in new window


but this does nothing. With research, it seems I may need to use JSON Web Tokens. Is that the path I should go down? Any other recommended approach?
0
How do I host my html, css, handlebars, node, express, mysql websites?  

I see all kind of hosting plans with website builders. But, I am not sure what to look for in hosting when "you" build your own sites.

Thanks,
Ed
0
Here's my code:

exports.deletePost = (req, res, next) => {
  const postId = req.params.postId;
  Post.findById(postId)
    .then(post => {
      if (!post) {
        const error = new Error("Could not find post.");
        error.statusCode = 404;
        throw error;
      }
      //check login user
      clearImage(post.imageUrl);
      return Post.findByIdAndRemove(postId);
    })
    .then(result => {
      console.log(result);
      res.status(200).json({ message: "Deleted post!" });
    })
    .catch(err => {
      if (!err.statusCode) {
        err.statusCode = 500;
      }
      next(err);
    });
};

Open in new window


Line #12, it says return Post.findByIdAndRemove(postId).

I was always under the impression that once you invoke the "return" dynamic, you're exiting the flow of the code at that point. Yet, in this case, it proceeds to the next "then" clause.

Why?

The code works, but I want to know why the continues to the next "then" clause despite the fact that there's a "return" dynamic in place.
0
I was show how to access the responsXML once for my list.  I am trying figure out how to get to the nodes again.  The last time I did it, it was with Chrome Developer tools in the browser.

I have a function like this:

function myFunction(responseXML) {
		console.log(responseXML);
		var itemList = [];
		console.log(responseXML.getElementsByTagName("entry"));
		for (var i = 0; i < responseXML.getElementsByTagName("entry").length; i++) {
			id = responseXML.getElementsByTagName("entry")[i].childNodes[0].childNodes[0].nodeValue;
			title = responseXML.getElementsByTagName("entry")[i].childNodes[20].childNodes[0].childNodes[5].childNodes[0].nodeValue;
			header = responseXML.getElementsByTagName("entry")[i].childNodes[20].childNodes[0].childNodes[7].childNodes[0].nodeValue;
			urlDescription = responseXML.getElementsByTagName("entry")[i].childNodes[20].childNodes[0].childNodes[8].childNodes[0].childNodes[0].nodeValue;
			url = responseXML.getElementsByTagName("entry")[i].childNodes[20].childNodes[0].childNodes[8].childNodes[1].childNodes[0].nodeValue;
			methodType = responseXML.getElementsByTagName("entry")[i].childNodes[20].childNodes[0].childNodes[9].childNodes[0].nodeValue;
			itemList.push(new Item(id, header, title, url, urlDescription, methodType));
		}

Open in new window

0
Learn SQL Server Core 2016
LVL 20
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

I have a node.js express web application I’d like to covert to a native app for iOS and Android so that I can use the smartphone Bluetooth interface to connect to peripheral devices (Raspberry Pi and/or Arduino). I’d like to develop one app for both iOS and Android and am proficient with JavaScript so am leaning towards React Native, although I have no experience with React. I’m also considering Swift and Flutter. I’d like to develop in my IDE of choice, VS Code, if possible.
This project is foremost for learning so a long learning curve is not an issue. Main considerations are leveraging my web application dev experience and learning new tech that will last.
Any input is welcome!
0
In my node app I have to insert a new XMLnode for identify it later. I developed some code where I expected the right result.
It is really simple:

var xmlDoc = new DOMParser().parseFromString(dataRegelWerk);  //Incomming data
if(allok == false){
                var root = xmlDoc.documentElement;

                var varselem = xmlDoc.getElementsByTagName('vars')[0];
                var newEle = xmlDoc.createElement('TCafe');
                var att1 = xmlDoc.createAttribute("initvalue");
                att1.value = "1";
                var att2 = xmlDoc.createAttribute("type");
                att2.value = "int";
                newEle.setAttributeNode(att1);
                newEle.setAttributeNode(att2);

                root.insertBefore(newEle, varselem);
            }

var myFile = serializer.serializeToString(xmlDoc); //Put back to string to store in db

Open in new window


This is the original formatted XML

<xml xmlns:xi="http://www.w3.org/2001/XInclude">

   <vars>
....

Open in new window


I tried to insert before "vars" and the result is

<xml xmlns:xi="http://www.w3.org/2001/XInclude">

    <TCafe initvalue="1" type="int"/><vars>

Open in new window


But I expected

<xml xmlns:xi="http://www.w3.org/2001/XInclude">

    <TCafe initvalue="1" type="int"/>

       <vars>

Open in new window


Is there anything wrong with my code or do I expect a wrong thing? Maybe I have to close the new XMLNode? (I expected the last / will do it.
Any help will be great.
0
I  have a node.js API and a next.js frontend application. The login is working for the most part. But if I open google dev tools and I change the value of the token cookie and try to access the secret page again, it still lets me. Shouldn't it kick me out because the token is no longer the same?

Here is the backend where I check login credentials and then create the token.

exports.login = async (req, res, next) => {
  // check if email exists
  const user = await User.findOne({ email: req.body.email });
  if (!user)
    return res.status(400).send({ errors: ["Invalid login credentials"] });

  //email exists, check password
  const validPass = await bcrypt.compare(req.body.password, user.password);
  if (!validPass)
    return res.status(400).send({ errors: ["Invalid login credentials"] });

  // create jwt token
  const token = jwt.sign(
    { email: user.email, _id: user._id },
    process.env.TOKEN_SECRET,
    { expiresIn: "1h" }
  );
  // add token to header
  res.header("auth-token", token).send(token);
};

Open in new window

Then here is the frontend code for the login where I set the cookie with the token value from the server:

  handleSubmit = async event => {
    const { email, password } = this.state;
    event.preventDefault();
    const user = {
      email,
      password
    };
    // client side validation
    const errors = this.validate(user);
    this.setState({ errors: errors || {} });
    if (errors) return;

    try {
      const response = await login(user);
      const token = response.data;
      cookies.set("token", token);
    } catch (ex) {
      if (ex.response) {
        const errors = ex.response.data.errors;
        this.setState({ errors });
      }
    }
  };

Open in new window

Then I created a route which you can only access if logged in:

Secret.getInitialProps = async ctx => {
  await handleAuthSSR(ctx);
  const response = await axios.get("http://localhost:8000/api/user");

  return {
    users: response.data
  };
};

Open in new window

Here is the auth function (I am using next-cookies)

import nextCookie from "next-cookies";

export const handleAuthSSR = ctx => {
  const { token } = nextCookie(ctx);

  if (ctx.req && !token) {
    ctx.res.writeHead(302, { Location: "/login" });
    ctx.res.end();
    return;
  }
  if (!token) {
    console.log("no token found");
    Router.push("/");
  }

  return token;
};

Open in new window

0
Here's my code in full:

require("dotenv").config();
const { validationResult } = require("express-validator/check");
const mongoose = require("mongoose");
const Profile = require("../models/profile");
const ClientId = process.env.CLIENTID;
const Secret = process.env.SECRET;
const Callback = process.env.CALLBACK;

//this is the empID you're getting from AHA
const empID = 7747;

//get today's date
let date_ob = new Date();

// current date
// adjust 0 before single digit date
let date = ("0" + date_ob.getDate()).slice(-2);

// current month
let month = ("0" + (date_ob.getMonth() + 1)).slice(-2);

// current year
let year = date_ob.getFullYear();

// prints date in YYYY-MM-DD format
let today = year + "-" + month + "-" + date;

const FitbitApiClient = require("fitbit-node");
const client = new FitbitApiClient({
  clientId: ClientId, //client_id
  clientSecret: Secret, //client secret
  apiVersion: "1.2" // 1.2 is the default
});

exports.getCallback = (req, res, next) => {
  const yesterday_raw = new Date(new Date().setDate(new Date().getDate() - 1));
  const yesterday = yesterday_raw.toISOString().slice(0, 10);

  client.getAccessToken(req.query.code, Callback).then(result => {
    var requests = [
      client.get("/profile.json", result.access_token), //0
      client.get("/activities/date/today.json", result.access_token), //1
      //client.get("/sleep/date/" + yesterday + ".json", result.access_token), //2
      client.get("/sleep/date/today.json", 

Open in new window

0
Here's what I've got:

client.get("/sleep/date/2019-11-05.json", result.access_token), //2

...and this generates an array. One of the values in that array is "REM" and I retrieve it like this:

const rem_sleep = JSON.stringify(data[2][0].summary.stages.rem); //minutes in deep REM sleep

Here's my dilemma: The user may not have worn their Fitbit to bed last night and when that happens, "rem_sleep" will be returned as "undefined."

I don't want that. Especially since I need a valid digit to enter into the database this project is going to be hooked up to.

So, here's what I tried:

const deep_sleep = JSON.stringify(data[2][0].summary.stages.rem); //minutes in deep REM sleep
        if (deep_sleep > 0) {
          const rem_sleep = deep_sleep;
        } else {
          const rem_sleep = 0;
        }
        res.send(rem_sleep);

As you might suspect, "rem_sleep" comes back as undefined .

I'm learing that with JavaScript, constants stay credible within the scope of their particular "block."

That said, how can I pull this off?

I need whatever it is that I can do in Javascript that equates to an IF clause that provides me a genuine value and not something that comes back "undefined."

What do you think?
0
Here's what I'm using to get yesterday's date:

const yesterday_raw = new Date(new Date().setDate(new Date().getDate() - 1));
console.log(yesterday_raw);

It works fine, but I need to format it according to YYYY-MM-DD. I've seen a number of approaches on the Internet, but they all look kind of clunky.

I figured I would bring it before the ninjas and see if someone's got an easy way of formatting the above as YYYY-MM-DD.

Thoughts?
0
Here's the array I'm getting back from Fitbit...

{"summary":{"water":0},"water":[]}

This is part of a much larger body of data. I'm retrieving it using this:

res.send(data[4][0]);

My question is two-fold: First I want to get to the "0" value. From what I understand, "summary" is an Object based on the way it's documented using curly braces. Within that Object, I have both Properties and Values. Properties can be arrays within themselves which is what I have here. I have a "summary" Object with two properties, both of which are called, "water." One is a Property with a single value, the other is an Array.

If I want to get to the first "water" property that has a value of "0," I would think I would do this:

res.send(data[4][0].water

...correct? The response I get is "[]."

If I do this:

res.send(data[4][0]["water"]);

I get "[]."

Why? I would expect "res.send(data[4][0].water" to give me "0," and it doesn't.

Why not?
0
Here's the array:

[
   {
      "activities": [
         {
            "activeDuration": 1280000,
            "activityLevel": [
               {
                  "minutes": 0,
                  "name": "sedentary"
               },
               {
                  "minutes": 3,
                  "name": "lightly"
               },
               {
                  "minutes": 10,
                  "name": "fairly"
               },
               {
                  "minutes": 9,
                  "name": "very"
               }
            ],
            "activityName": "Walk",
            "activityTypeId": 90013,
            "averageHeartRate": 88,
            "calories": 134,
            "duration": 1280000,
            "elevationGain": 0,
            "hasGps": false,
            "heartRateLink": "https://api.fitbit.com/1.2/user/-/activities/heart/date/2019-11-07/2019-11-07/1sec/time/05:10:57/05:32:17.json",
            "heartRateZones": [
               {
                  "max": 82,
                  "min": 30,
                  "minutes": 3,
                  "name": "Out of Range"
               },
               {
                  "max": 114,
                  "min": 82,
                  "minutes": 19,
                  "name": "Fat Burn"
               },
               {
                  "max": 139,
                  "min": 114,
                  "minutes": 0,
                  "name": "Cardio"
               },
               {
                  

Open in new window

0
I'm building a Fitbit API and we're going great guns but I've run into a snag and I'm confident it's due to my being new to Node.js.

This works:

exports.getCallback = (req, res, next) => {
	client.getAccessToken(req.query.code, 'http://localhost:3000/callback')
	.then(result => { 
	// use the access token to fetch the user's profile information
	//client.get("/profile.json", result.access_token)
	client.get('/activities/date/2019-11-07.json', result.access_token)
		.then(results => {
			console.log(results[0].goals.calories);
			//res.send(results[0]);
		}).catch(err => {
			const error = new Error(err);
			error.httpStatusCode = 500;
			return next(error);
		});
		
	});
};

Open in new window


...and this works:

exports.getCallback = (req, res, next) => {
	client.getAccessToken(req.query.code, 'http://localhost:3000/callback')
	.then(result => { 
	// use the access token to fetch the user's profile information
	//client.get("/profile.json", result.access_token)
		client.get("/activities/calories/date/today/1d.json", result.access_token)
		.then(answers => {
			.then(answers => {
			res.send(answers[0]["activities-calories"][0].value);
		}).catch(err => {
			const error = new Error(err);
			error.httpStatusCode = 500;
			return next(error);
		});
	});
};

Open in new window


Now, are you ready for this?

I've got to retrieve information that's coming from multiple endpoints. So, I tried to do this:

exports.getCallback = (req, res, next) => {
	client.getAccessToken(req.query.code, 'http://localhost:3000/callback')
	.then(result => { 
	// use the access token to fetch the user's profile information
	//client.get("/profile.json", result.access_token)
	client.get('/activities/date/2019-11-07.json', result.access_token)
		.then(results => {
			console.log(results[0].goals.calories);
			//res.send(results[0]);
		}).catch(err => {
			const error = new Error(err);
			error.httpStatusCode = 500;
			return next(error);
		});
		[b]client.get("/activities/calories/date/today/1d.json", result.access_token)
		.then(answers => {
			.then(answers => {
			res.send(answers[0]["activities-calories"][0].value);
		}).catch(err => {
			const error = new Error(err);
			error.httpStatusCode = 500;
			return next(error);
		});[/b]
	});
};

Open in new window


And I get this error:

         .then(answers => {
                        ^

SyntaxError: Unexpected token .

I'm assuming it's because I'm going about this the wrong way.

I need two sets of information, one from "client.get(activities)' and one from "client.get('activites/calories')."

How do I make that happen?
0
Become a Microsoft Certified Solutions Expert
LVL 20
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

I'll open up a Node application, make some changes and then...

I'll get an error that says:  Error: listen EADDRINUSE: address already in use :::3000

I'll go to my Command Line and enter: netstat -aon. I'll get a list of ports and who's using what and I'll find Port 3000, make a note of the PID and then do something like this:

Taskkill/PID <PID number> /F

I'll get a message that says the process has been killed and I'll move on from there.

But I'm at a point where I can't even do CNTRL C and kill my server so I can upload a package or whatever I need to do. I'll use "process exit" and then my Git Bash will stop responding and I have to start all over.

I'm getting things done, but I wanted to reach out and get some other eyes on this to figure out if there's something wrong that I need to fix. On other computers, I don't have that problem, but there's something awry here and I don't know what.

Thoughts?
0
I'm working my way through fitbit-node and I'm trying to understand how I can access various pieces of information that go beyond the "profile," which I've been able to successfully retrieve,  but I need calories burned, heartbeat etc and that's where I'm getting lost.

First of all, here's the working code:

// initialize the express application
const express = require("express");
const app = express();
const path = require("path");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const token="";

//const authorizeRoutes = require("./routes/authorize");

app.use(bodyParser.json());
//app.use("/authorize", authorizeRoutes);

// initialize the Fitbit API client
const FitbitApiClient = require("fitbit-node");
const client = new FitbitApiClient({
	clientId: "BOGUS", //client_id
	clientSecret: "BOGUS_AGAIN", //client secret
	apiVersion: '1.2' // 1.2 is the default
});

// redirect the user to the Fitbit authorization page
app.get("/authorize", (req, res) => {
	// request access to the user's activity, heartrate, location, nutrion, profile, settings, sleep, social, and weight scopes
	res.redirect(client.getAuthorizeUrl('activity heartrate location nutrition profile settings sleep social weight', 'http://localhost:3000/callback')); //callback url
});

// handle the callback from the Fitbit authorization flow (working code)
app.get("/callback", (req, res) => {
	// exchange the authorization code we just received for an access token
	

Open in new window

0
I want to utilize some "best practices" as I build the API you see below, as far as using routes, models and controllers etc.

The code below is something I'm using from "fitbit-node." It works just fine, however. I want to take some of what resonates as that which belongs in a "routes" directory and move it so, when I'm all finished, I can upload it as something that looks and feels like a complete and accurate app.

At least, that's what I'm thinking.

Here's my code:

// initialize the express application
const express = require("express");
const app = express();
const path = require("path");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
[b]//const authorizeRoutes = require("./routes/authorize");[/b]

app.use(bodyParser.json());
[b]//app.use("/authorize", authorizeRoutes);[/b]

// initialize the Fitbit API client
const FitbitApiClient = require("fitbit-node");
const client = new FitbitApiClient({
	clientId: "CLIENT_ID", //client_id
	clientSecret: "SECRET", //client secret
	apiVersion: '1.2' // 1.2 is the default
});

// redirect the user to the Fitbit authorization page
app.get("/authorize", (req, res) => {
	// request access to the user's activity, heartrate, location, nutrion, profile, settings, sleep, social, and weight scopes
	res.redirect(client.getAuthorizeUrl('activity heartrate location nutrition profile settings sleep social weight', 'http://localhost:3000/callback')); //callback url
});

// handle the callback from

Open in new window

0
I'm working my way through a couple of tutorials that walk you through how to create an API that retrieves Fitbit info. The content is great and every educational, but I'm stuck and I need some help.

First of all, I'm using  "fitbit-node" (https://github.com/lukasolson/fitbit-node). With that, I've been able to successfully retrieve "profile.json" which seems to be the starting point for any API.

The "app.js" that's included as part of the example, looks like this:

// initialize the express application
const express = require("express");
const app = express();

// initialize the Fitbit API client
const FitbitApiClient = require("fitbit-node");
const client = new FitbitApiClient({
	clientId: "22BD5D", //client_id
	clientSecret: "9677a6cdf63836e26d0617e9ac2c38f8", //client secret
	apiVersion: '1.2' // 1.2 is the default
});

// redirect the user to the Fitbit authorization page
app.get("/authorize", (req, res) => {
	// request access to the user's activity, heartrate, location, nutrion, profile, settings, sleep, social, and weight scopes
	res.redirect(client.getAuthorizeUrl('activity heartrate location nutrition profile settings sleep social weight', 'http://localhost:3000/callback')); //callback url
});

// handle the callback from the Fitbit authorization flow
app.get("/callback", (req, res) => {
	// exchange the authorization code we just received for an access token
	client.getAccessToken(req.query.code, 'http://localhost:3000/callback').then(result => { 

Open in new window

0
I'm working with a fully functional Node.js code that interacts with the Fitbit API.

Being somewhat new to Node, however, has me in a spot where I need a little guidance.

The code looks like this:

// initialize the express application
const express = require("express");
const app = express();

// initialize the Fitbit API client
const FitbitApiClient = require("fitbit-node");
const client = new FitbitApiClient({
	clientId: "CLIENT_ID", //client_id
	clientSecret: "CLIENT_SECRET", //client secret
	apiVersion: '1.2' // 1.2 is the default
});

// redirect the user to the Fitbit authorization page
app.get("/authorize", (req, res) => {
	// request access to the user's activity, heartrate, location, nutrion, profile, settings, sleep, social, and weight scopes
	res.redirect(client.getAuthorizeUrl('activity heartrate location nutrition profile settings sleep social weight', 'http://localhost:3000/callback')); //callback url
});

// handle the callback from the Fitbit authorization flow
app.get("/callback", (req, res) => {
	// exchange the authorization code we just received for an access token
	client.getAccessToken(req.query.code, 'http://localhost:3000/callback').then(result => { //callback url
		// use the access token to fetch the user's profile information
		[b]client.get("/profile.json", result.access_token)[/b]
		[u]//client.get ("/1/user/[user-id]/[resource-path]/date/[date]/[period].json", result.access_token)[/u]
		.then(results => {
			res.send(results[0]);

Open in new window

0
I'm using "npm fitbit-node" and I am poised on the threshold of great things!

Here's the "app.js" file and I've emboldened that section of the code that I've got a question about:

// initialize the express application
const express = require("express");
const app = express();

// initialize the Fitbit API client
const FitbitApiClient = require("fitbit-node");
const client = new FitbitApiClient({
	clientId: "CLIENT_ID", //client_id
	clientSecret: "CLIENT_SECRET", //client secret
	apiVersion: '1.2' // 1.2 is the default
});

// redirect the user to the Fitbit authorization page
app.get("/authorize", (req, res) => {
	// request access to the user's activity, heartrate, location, nutrion, profile, settings, sleep, social, and weight scopes
	res.redirect(client.getAuthorizeUrl('activity heartrate location nutrition profile settings sleep social weight', 'http://localhost:3000/callback')); //callback url
});

// handle the callback from the Fitbit authorization flow
app.get("/callback", (req, res) => {
	// exchange the authorization code we just received for an access token
	client.getAccessToken(req.query.code, 'http://localhost:3000/callback').then(result => { //callback url
		// use the access token to fetch the user's profile information
		[b]client.get("/profile.json", result.access_token)[/b]
		[u]//client.get ("/1/user/[user-id]/[resource-path]/date/[date]/[period].json", result.access_token)[/u]
		.then(results => {
			res.send(results[0]);
			

Open in new window

0

Node.js

278

Solutions

373

Contributors

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.