Blog

Using Backendless API with Node.js

by on March 29, 2013

The Backendless API for JavaScript can be used not only from the browser-based JavaScript applications but also from a Node.js program. Using the API is very straight-forward. The instructions below describe the steps for setting up and running a basic Node.js example with Backendless. The example demonstrates registering a user with your Backendless application. It gathers email address and password and uses the User Registration API call to create an account.

  1. Just like with the browser JavaScript, an application must be identified using the application ID and a secret key. To get the ID and the key, login to the Backendless console, create/select your application and click the Manage icon. The default subsection is App Settings:
  2. Save the code shown below into a file. Name the file example.js.
  3. Use the “Copy” buttons to copy the application id value and the secret key for JavaScript. The copied values must be assigned to the “appId” and “secretKey” variables accordingly.
  4. Download the Backendless JavaScript library file and save it in the same directory where you created example.js (step 2).
  5. Open a command prompt window and run the example using the following command:
    node example.js

The source code of the example is below (double-click the code to remove the highlighting, or click the <> button to toggle it):

var Backenless = require("./backendless");
var readline = require('readline');
var appId = 'COPY YOUR APP ID HERE';
var secretKey = 'COPY YOUR SECRET KEY HERE';
var appVer = 'v1';
Backendless.initApp( appId, secretKey, appVer );
var user = new Backendless.User();
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
rl.question( "input email address ", function( answer ) {
  user.email = answer;
  rl.question( "input password ", function( answer ) {
    user.password = answer;
    console.log( "please wait ..." );
    rl.close();
    try
    {
      console.log( "Registering user account : ", user );
      var register = Backendless.UserService.register(user, new Backendless.Async(function( data ){
       console.log( "server data ", data );
       console.log( "User successfully created ", user );
     },function( e ) {
       e = e || {};
       console.log(e.massage || "Unable to register user" );
    }
    ));
   }
   catch( e ) {
     console.log( e.message );
   }
  });
});

Have fun and please let us know if you run into any problems!

Leave a Reply