Intro to HTTP with Node

If you’re new to Node, the HTTP protocol is something you’ll definitely need to become familiar with. When I first started learning Node, I was coming from a LAMP background and was surprised at how very little Node offers out of the box. While writing web applications with PHP, you tend to forget about how much Apache does for you under the hood. Once you have a LAMP server setup, PHP can easily access, send and receive HTTP request with very little work. Unfortunately, there’s a lot more leg work to be done with Node.

Note: Before I completely scare you away from Node, there are a bunch of excellent modules out there that will do this work for you. This is merely a post to show you what happens behind these modules.

HTTP Basics

HTTP is the main protocol used to fetch data from websites. When you first came to http://danramosd.com, you made a single HTTP request to view the contents of this site. More specifically, you made an HTTP GET request. When interacting with web applications you will usually use GET and POST methods which are said to be the HTTP “verbs”. These are not the only HTTP verbs out there, but they cover a large majority of all HTTP requests.

GET Requests

These requests are made when you need to retreive data from the server. If you ever examined the URL of a request after searching on a site you’ll most likely see the contents of your search in the address bar. This URL could look something like this:

http://www.site.com/search?term=intro-to-http&category=programming

A typical web application will parse the URL and turn your query parameters into a key/value pair that could look like this:

term = “intro to http”
category = “programming”

The web application can then use this information to query its database to find an article name that contains “intro to http”, within the category of “programming”. Since the web application uses data from the URL, you could send this link to a friend and they would be able to see the same search results without having to perform the search themselves.

It should also be noted that GET requests don’t just fetch web pages, but also the contents used by web pages such as images, CSS and JavaScript files. When a browser retrieves the HTML from a web page it parses the DOM for references to external files. Once it finds the references, it performs additional HTTP requests to download the file contents.

POST Requests

POST requests are typically used when you want to send data to the server. The most common use case for POST requests are forms, and sending sensitive data. When you’re filling out a form that contains sensitive data (i.e credit card info), the data is sent in a message body (more on this shortly) as part of the POST request. This transfers the data to the server without having to display your credit card information in the actual URL.

HTTP Headers

Every HTTP request, regardless of the verb, sends a request header. These headers provide meta-data about the actual request. It tells the server things about our browser information, type of data we’re expecting back, cookie information and more.

Message Body

As mentioned before, POST requests send a message body along with the header. The message body is sent as key/value pairs, similar to that of the GET request, but is transparent to the user and not visible in the URL itself.

HTTP with Node

Now we have a 100 level HTTP background, lets see how this all works in Node. Assuming you already have Node installed, create a file with the following content and save it as app.js.

var http = require('http'),
url = require('url');
http.createServer(function (req, res) {
if( req.method === 'GET'){
get( req, res )
}
else if( req.method === 'POST' ){
post( req, res )
}
}).listen(3000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:3000/');

The first two lines import the required core Node modules use by our application and assigns them to local variables. Modules are self contained pieces of code that perform specific functionally and are used widely throughout Node development.

Once the modules are loaded, we create an HTTP server where all requests to the server are passed to the callback. The callback is handed the request object which contains the headers, post body (if applicable) and some other various information. Each request has a method property (HTTP verb), which we check for and pass off to their respective function. Lastly, we tell our server to listen on port 3000.
Our server is now ready to start accepting requests, but we still need to implement the functions that handle each request. Lets start with the get() function.

var get = function( req ,res ){
var queryParameters = url.parse(req.url,true).query;
console.log('Params', queryParameters)
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('GET request success!\n');
}

Just like the callback in our createServer function, our get() and post() functions accept the same parameters. When a GET request comes in, we grab the URL via req.url and pass it off to url.parse(). This allows us to parse a query string and convert it to a JavaScript object for easier use.

In order to complete the request we need to send a response back to the client. Similar to the request headers, the server will send a response header with our content. This can be done by calling writeHead() on the res object. The first parameter specifies the HTTP response code, 200 in this case, which means the request went through OK, and the second parameter specifies additional header options. We’re just going to send back some text so we set the Content-Type to text/plain. Wrapping things up, a string of plain text is sent back to the client and we end the connection.

Last but not least is our post() implementation, which is slightly different than get().

var post = function( req ,res ){
var body = '';
req.on('data', function( chunk ){
body += chunk
})
req.on('end', function(){
console.log('body', querystring.parse(body))
})
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('POST request success!\n');
}

As mentioned earlier, POST requests send their data in post body, not in the URL. The post body is not immediately ready once the headers come in, so two event listeners are placed on the request object. One for when data comes in and another when all data has been received. Since the data doesn’t come in all at once, each chunk of data is appended to a String variable called body. Once all our post body data has been received, the end event listener is fired. Similar to url.parse(), querystring.parse() converts the data into a JavaScript object. Finally, the header is created and the response is sent back to the client.

Testing GET and POST requests

Congratulations, you’ve just written a web server in Node! That’s great and all but how do you go about testing it? Starting up the server is as simple as running:

$ node app.js

Pop open a browser, navigate to 127.0.0.1:3000 and should see GET request success!. As you can see, the GET request is working fine, but now we need a way to test our POST. Building out a form is one way to do this, but often requires some more work and isn’t very easy to customize.

There are a bunch of ways to test POST requests (or all HTTP request for that matter), but my favorite way by far is to use the Postman Chrome plugin. This plugin will make server and API development (a post for another day) extremely easy moving forward.

React.js Live Search

The React.js site has a bunch of great documentation on getting started, but unfortunately real world examples are few and far between. Taken straight from their home page, “React is a javascript library for building user interfaces”. Now a lot of people try to compare React vs Angular, Backbone or some other kind of client side MV frameworks, but they’re kind of missing the point. Although React could technically be used as a full MV framework, I believe it’s better off used as the V portion of your MV* application.

React’s API is pretty minimal, but damn powerful. Here’s a high level overview of how the framework is implemented:

  • React applications are built by custom defined, reusable components.
  • Each component has a private state and public properties.
  • A component has the ability to render child components creating a parent-child relationship. The parent can pass properties to the child via tag attributes.
  • When a component’s state changes, React will efficiently re-render the DOM based upon the virtual DOM difference.

Creating your first component

React gives you the option of writing your components with plain ol’ JavaScript, or JSX which is an XML-like syntax. In this tutorial we’ll be covering the JSX implementation. To create a component, simply define some properties within React.createClass() and assign it to a variable.

var HelloMessage = React.createClass({
render: function() {
return <div>{'Hello ' + this.props.name}</div>;
}
});

As you can see, this isn’t 100% valid JavaScript, but React’s JSX transformer library will compile the code for you so it can be used by the browser.

Each component must have a render function, defining how the component should render in the DOM. The above code snippet simply defines the component, in order to render the actual component we run the following.

React.renderComponent(<HelloMessage name="John" />,
document.getElementById(?container?)
);

The variable name HelloMessage that was assigned to the component can now be called as a custom tag. If you’re familiar with Angular, this is similar to a directive. When rendering a component you can pass all of its properties in as a tag attribute. In this case we set name="John", which can then be accessed inside the class definition as this.props.name.

A few notes on JSX

JSX can be compile both client and server side. For demo purposes we’ll be using the client side implementation, but for production code you should always precompile on the server. In order to use JSX in the browser there are a couple requirements we have to fulfill.

<!-- Access to React?s library -->
<script src="js/vendor/react/react.js"></script>
<!-- Ability to write JSX in our main.js -->

<!-- Ability to write JSX in our main.js -->
<script src="js/vendor/react/JSXTransformer.js"></script> 

<!-- Must define text=?text/jsx? for this file to be compiled -->
<script src="js/main.js" type="text/jsx"> </script>

Our final step is to call the JSX doc block at the top of our main.js file.

/** @jsx React.DOM */

Live search component definition

Our small app will consist of 3 components.

  • SearchInput – An input field that listens for changes
  • SearchResults – An unordered list that display results based upon the SearchInput value
  • LiveSearchContainer – A master component which passes data from the SearchInput to SearchResults

SearchInput

var SearchInput = React.createClass({
render: function() {
return (
<div>
<input type='text' placeholder='Search' onChange={this.props.query} />
</div>
);
}
});

The render function for this component is very minimal and straightforward. The most important part of this component is onChange={this.props.query}. As stated above, we need a way for SearchInput to talk to the LiveSearchContainer. We do this by setting an onChange event listener on the input field, and pass the event off to this.props.query. The query property is nothing more than a function defined in LiveSearchContainer, and passed as a property to the SearchInput component.

SearchResults

var SearchResults = React.createClass({
render: function() {
var results = this.props.data.map(function( item ){
return <li>{item}</li>
})
return (
<ul>
{results}
</ul>
);
}
});

When the results of the search are updated, SearchResults is passed the resulting data from LiveSearchContainer. Iterating through this.props.data, a list item is created for each result.

LiveSearchContainer – Tying everything together

var LiveSearchContainer = React.createClass({
getInitialState: function(){
return {data:[]};
},
query: function(e){
var results = []
if( e.target.value !== "" ){
var reg = new RegExp( e.target.value )
results = $.map(data, function( item ) {
if ( item.match(reg) !== null) {
return item
}
});
}
this.setState({
data:results
})
},
render: function() {
return (
<div>
<SearchInput query={this.query} />
<SearchResults data={this.state.data} />
</div>
);
}
});

Jumping straight to the render function, you’ll see we create two DOM
elements based upon the component definitions above. Each element is passed a different attribute, which we accessed via this.props.*.

Whenever the user types into the SearchInput field, the event and data is passed off to the LiveSearchController’s query() function. This value is used to perform a RegEx search on an arbitrary array of strings. Any matches are pushed onto an array, and then updates the component’s state via this.setState(). The SearchResults component is assigned a property that uses LiveSearchController’s state.data. If a component’s state ever changes, React will automatically re-render the component for us. In this case SearchResults will re-render and show the updated results.

Wrapping up

With all the components created, the only thing left to do is create a data source and render LiveSearchContainer.

var data = ['javascript', 'node', 'html', 'css', 'react', "php", "programming", "xml", "json"];
React.renderComponent(
<LiveSearchContainer data={data} />,
document.getElementById('container')
);

To view the full source code checkout the project on github.

Steve Blank – Startup in a box

Aside from being a great speaker, Steve Blank offers some phenomenal actionable advice for aspiring entrepreneurs.  The video is pretty long but well worth the time.

Some key points:

  • Startups aren’t just smaller versions of bigger companies.
  • Business plans are not the same as business models.
  • Startups are constantly searching for their business model which he defines as a repeatable process that generates profitable revenue.
  • A business plan is the plan of execution on a proven business model.  Large companies already have a business model in place, it’s the job of the C level execs to execute on this plan

Idea, Research, Implementation

Idea

A lot of personal trainers run their businesses strictly online.  They promote themselves through Instagram, Twitter, Facebook and other social media outlets.  To sign up for their program, the prospective client would email them with their goals.  This lead me to believe there are usually several emails exchanged between the trainer and prospective client with multiple Q n A’s.  This could be manageable if your client base is small, but what do you do when you reach 5-10+ clients?  This lead me to also question how they handle handled the rest of their business between scheduling, creating workouts, collecting payment, storing workout/nutrition logs, and managing contact information.

Competitive Analysis

Searching around online I found there is a severe lack of quality CRM solutions for fitness professionals.  In fact, it appears there is just one dominate company in this field.  While they have tons of features and seem to be a well established company I looked for their weak links.  This allows me to differentiate myself as a competitor, while solving problems that their current customers have with them.  The two major points that stood out are price and design.  Their initial package starts at $70/mo which seems pretty high for a self employed trainer.  By charging slightly less I can appeal to a larger audience, and justify my lack of features MVP.  Also, their design seemed overly complicated, and something from 2005.  I want to build a product that’s easy to use and aesthetically pleasing.

Market Research

This is a step I’ve neglected in all my previously failed startup attempts.  By doing the market research ahead of time I can validate my idea and prioritize features.  Aside from gaining knowledge this helped me start building relationships with prospective clients once I’m ready for launch.  The research also showed that I could make this app not just for personal trainers, but athletic and physical therapist as well.  You can checkout my market research notes here.

Implementation

Based upon my research, I came up with the following features:

  • Calendar/Scheduling with automated text message reminders
  • Client payment processing
  • Store workouts and nutrition programs in one location
  • Track workout log and performance metrics for clients
  • Ability to export financials to Quickbooks
  • Assessment forms

This is obviously too many features for an MVP so I’m sticking with the three most requested.

  • Scheduling & automated reminders – Pretty straight forward, create a calendar with your training sessions and send out automated email/text message reminders 1 day and 1 hr before each session.
  • Custom forms – These forms can be used for various reasons.  Collecting medical and contact info from the client, custom performance evaluation, workout logs for clients, etc.
  • File Storage – Give trainers the ability to upload their workouts, nutrition programs and pictures.  This provides them with a centralized location for all their info and could attach these files to specific clients or email them out from within the app.

BodStrong API & Tech Overview

Users

Standard CRUD operations + sessions registration via sign_in and sign_out

  • POST /users/sign_in
  • POST /users/sign_up
  • POST /users/sign_out

 

Calendar (google calendar)

A single calendar resource will be created for each user on the backend.  Users will be able to CRUD events, while the backend will use the ‘watch’ event to update our TXT message reminders.  TODO: Investigate the events gadget

Automated TXT messages (Twilio)

Cron job for sending text messages

  • Send 1 hr, and 24 hrs in advance
  • Need to know who to text, the event name, time, and who the event is with.

Custom Forms(JotForms)

Give users the ability to create custom forms.  The forms could be used to collect client medical/contact info or generate a workout/nutrition programs.

BodStrong Fitness CRM – Market Research Responses

Below is a list of the market research I preformed before deciding to move forward with my idea.  The notes are left in their original form and are intended to remind me of what is important to the users.


 

Scott – willing to help promote and beta test once ready

Q. What kind of software, if any, do you use to create workout/nutrition programs, track client progress and schedule clients?

A. I use excel for tracking and creating programs for all my clients. Works great

Q. How do you collect payments from your clients?

A. I either get a check, cash or cc payment through an iPhone card reader.

Q. What is the main way you grow your client base?

A. main way I grow my client base is through referrals.

Q. What is the top 1-3 pain points or tedious tasks you have as a trainer/business owner that software might be able to fix.

A. automatic emails sent to clients about payment/session times.

Q. Would you be willing to pay for a software solution if it met your needs (no hard feelings if you wouldn’t)?

A. No but I would love to be a sponsor and help promote your business with fellow PTs.


Nancy

Hi Dan- In answer to your questions-

1. I don’t use software, just pen and paper…I know- old school!
2. I use PayPal for online registrations
3. I grow my client base mainly through client referrals, offer them incentives
4. Keeping my workouts that I create in some sort of order. I’ve got lots of paper notes all over the place though it does work for me. I’d like to do a better job keeping client info in one place and then be able to categorize it for birthday shout outs or specials that I’m running.

Hope this helps. Let me know if I can do anything else for you. Have a great day! Enjoy the snowfall! Nancy

________________________________________________________________________

Sarah

Hi Dan,

Here are my answers to the questions

1) I am certified through NASM and they give you templates to download that go onto word to help create weekly, monthly, annual plans as well as a templates for that day’s workout.  To schedule clients I use the calendar in my phone so that I always have it on me.  To track client progress I use excel and just some notes.  This part is not as streamlined as I would like.

2) I collect payments through check and cash

3) Mainly I grow my client base through word of mouth.  I am working on social media but word of mouth is always the best.

4) I would love to have software that would have everything in one spot.  My schedule for clients.  I could click on the client see their personal workout schedule, track their results and see what their work out is for the day and easily look at the past workouts.  I would also love software that could easily compile all new work out moves, videos, articles I find.  Right now I just use my favorites folder on my laptop.  One pain point is when I make the class I see what they did in the previous session but I do not always remember what moves they have tried previously or what progressions they are up to.  I would like a way to keep that more readily available.

4) I would be willing to pay for software if it met my needs.  I would be much more likely to buy it if it was a one time cost as apposed to a monthly bill.

I hope these answers have helped! Let me know if you have any other questions.

Sarah


Brent – Notes are from our phone conversation

  • He uses/used google biz apps and excel for workouts
  • Was tedious to create workouts but now has a template that he just fills out
  • Checkout mytime app
  • Most clients come in same time every week
  • Big pain point – Confirmation of appts and reminders of apts and payments.
  • Availability calendar – not a huge need for him since he doesnt have standard hours.
  • He was using intuit which was a huge mess, now uses quickbooks and a book keeper
  • lots of clients travel
  • each client has their own folder w/ session info, workout logs, and how they paid
  • Would use an ipad over pen/paper
  • Would like to have a PDF that clients could fill out their medical info
  • Wants something on a laptop or ipad
  • Said that marketing/advertising is expensive and takes up too much time
  • In the future will want something that allows him to track leads but not needed now
  • $30-35/mo – Cheaper doesnt == better in his book.  He would rather have something that just works vs something very cheap
  • trainerspace.com – not a good UX
  • Not really looking to pay now, but def in the future when he grows

Julian - Certified Personal Trainer

Dan,

I’ve heard of the Yuma Scorpions. I played ball  at Appalachian State and Grambling. Tried out for Indy ball (Continental League) in Texas, but tore my hammy pretty bad during the 60 yard dash and decided to hang up my cleats afterwards in pursuit of a personal training career.

1. I’m pretty old fashioned. I run a 1800 sq ft fully equipped personal training studio.  I have an appointment book where I write my appointments, and I have a log in sheet where I keep track of used sessions. Also, I have a file folder system for measurements, workout programs, nutrition info, etc. I do this because It’s very inexpensive, easy,  and convenient.  Another reason I do this is because I normally don’t bring my laptop to work. I have a lot of independent contractors renting space from me and there’s a lot of people going in and out. I don’t want anything valuable of mine to come up missing. Anything internet related such as email etc I just use my cell phone.

2. I collect payments via Square, Paypal, Check, or Cash. I’ve been doing this for over 6 years and in that time I’ve only had one check bounce in which that client apologized and covered the costs of the bad check. Other than that, I’ve had absolutely no issues to date.

3. I grow my client base through referrals, social media, my website, and article writing.  I’ve used mailers, craigslist, news letters, google ads, yellowpage ads, etc and have had very little success. Return on investment in terms of paying for ads for clients in this business isn’t the way to go.  Reason being is people tend to research trainers, gyms, workout programs etc, but usually more often than not they aren’t ready to act. I’ve had tremendous success with social media giving my clients incentives to promote my business via their social media networks like Facebook check-in’s. Then when anyone in their network is interested in personal training, they’ve seen my name several times in connection with someone they know. This usually leads to them asking their friends about me and my clients telling them how much they enjoy working out with me etc.

4. The number one thing and only real thing that drives me crazy in this business is people who are unwilling to put in the work that is required to reach their goals. For instance, consistently showing up late for 30 minute appointments, missing sessions on a weekly basis, not adhering to dietary habits, the belief that just purchasing a training ensures their fitness success regardless of their exercise and dietary habits.  However, it’s also my job to help these people break people out of these habits and realize what it takes in order for them to reach their goals.

5. At this point in time, I wouldn’t feel the need to purchase software to improve my business.  However, it could be a strong possibility down the road. As of right now, without me my business plan doesn’t work.  Therefore, my business would only be valuable to someone who could provide the same service as me like another trainer.  Because of that, I’ll eventually move to a point where I’ll hire employees to start training clientele and I’ll move into a management role. This is where software would be key. I’d be able to track sessions, workout routines, nutritional programs, etc all online. This would make my business of more value to someone looking to purchase a turn key business.

Personally, I’m not at that level yet, but there are plenty of business around me who are.  If you haven’t already, I’d contact Funktional Fitness, Elite Sport in Fitness, Elite Personal Training, Fitness Defined, Body Fuzion Fitness, The Bar Fitness, Scott’s Training Systems, AZ Pro Physiques, and Pro Fitness. Those are just a few training studios off the top of my head that I know use software. Best of Luck to you Dan and I hope by answering these questions I could help you out.

__________________________________________________________________________

Wendy – Phone notes (conversation ended short as she had a client walk in)

  • Willing to try a new service
  • Big issue is having all of their info in one place
  • Big issue with mindbody not integrating with quickbooks.  She had to double enter everything
  • We got cut short, might not be a bad idea to reach back out to her

Jackie G - Physical Therapist – phone notes

  • They check in at the front desk w/ the secretary
  • it shows on her comp that they check
  • the schedule w/ the secretary
  • Sometimes she books herself
  • health-e-scheduler – is the calendar
    • She can view her treatment notes and excersizes, she keeps all her logs there
    • there are different colors whether or not the person is signed in and there
    • If they’re late it turns to red, if they cancel or no show after 15 mins then they turn into a different color
    • She can see all other therpist
  • At home workouts
    • Exercise pro to create client workouts
    • hep2go – home exercise program.  its a free website, just sign up
      • they have exercises that arent in exercise pro
      • all these ads pop up now and its really annoying, doesnt want to become a member
      • They lose the exercise
      • They like more exercises, better pictures
    • She builds it for each one individually, kind of a pain but only 5 mins.  Shes not thrilled with this.  She gives workouts only to like 50% of people
  • She just uses her laptop – not really a big deal if its an ipad or laptop
  • They need to write a documentation note for each visit, and the first one is always a very long one.  “ther-assist note”, connected to the scheduling, they can view the notes from scheduling, but cant edit.
    • ther-assist is just OK – you can use ‘pre made sentences’.  Thinks it could be more efficient.  Patient is a ___ yr old __, referred by Dr. ____.
    • Very tedious
    • They use full sentences vs just filling out attributes.
    • These notes are printed out as a treatement plan and then get faxed to the doctor.  The doctor sign and then signs back.
  • Company size – Physician owned practice.  A doctor owns it and a PT is connected to the DR office, 4 doctors, she works with 3 other PTs.  2 office – 50 to 75 people.  Everyone uses the same systems and pro

 

Chuck

  • two software systems – ther-assist (decent software)
  • exercise browser – home exercises
  • webpt – owned by a therapist.  Taking off right now
  • his fav software – anything medical is not user friendly
  • if google or apple made medical records it would be great
  • would prefer to use mad libs vs cliff notes (ther-asist)
  • The barrier – target private practices.  He works at a hospital, there is no way they are taking my software
  • Pain for them to make their own template
  • He could change it, but its a pain in the ass.
  • Scheduling
  • He would like to be able to send a text to every patient every 24 hrs and every hr before their patient
  • They fax everything to doctors – they are so far behind
  • they snail mail stuff
  • Paper stuff to make it electronic
  • they pay 2 companies to store the same data, they have to store paper documents for 3 years
  • $100/mo for notifications of text messages
  • The scheduling is used through ther-asist
  • he says its a pretty good system.  Same as jackie
  • web-pt.com
  • pilot with a small private practice  for a few months – ask for them to give a testimony, and then use that date to pitch to the next people

 

Greg – Physical Therapy (sports focused) via FB chat

Basic name and contact info for sure. Then maybe a DOB and the date the person first started working with you/how many sessions have occurred. This is sometimes important for insurance/legal reasons and would also be nice to have just for quick reference.

Oh and in terms of assessment info I think the template would be a good option and maybe have the option to make a few different ones. But also having just the ability to create whatever you want would be best. You can have the typical weight, bodyfat, vertical etc ready there and then maybe have the first option as “create your own” type of thing

and hopefully youll be able to add some kind of storage component and have all fo the programs for this client in a little box or dropdown menu or something

Another thought for the timeline of past sessions thing. Programs and training/rehab sessions are a lot of times planned based on a weekly approach so it might be easier to have a weekly timeline view to easily see how many days in a row theyve come or what days work best for the training program that fit the trainer/therapists schedule. also having the option of adding on a client’s calendar their planned competitoins coming up (ie games, marathons, meets, whatever) so as to be able to plan that way.