This post is also available in: esEspañol (Spanish)

The Javascript standard is constantly evolving and at times, it can be difficult to have features that match up with what is supported in a framework. Another issue you might run into is having an older tutorial that may not match up with what is on the cutting edge. The other day I was showing my brother how to set up express JS and saw that it didn’t use ES6. Here is how I walked him through it. You can find out more by reviewing our video course here.

Assuming that you already have node installed, create a new directory named myapp

mkdir myapp  && cd myapp

Then create your npm package file and make sure to set the entry point to app.js

npm init
npm install express body-parser --save

By default, you’ll be using ES5 and it’ll be required to use require to pull in modules. As we move forward with ES6 and beyond, it’s really best for us to start using ES6 classes as well as import and export statements. To do this, we’ll need Babel in order to interpret our ES6 syntax.

Lets pull in both ‘babel-cli and babel preset es2015” as dev dependencies as well as add the .babelrc file

npm install --save-dev @babel/core @babel/cli @babel/node
npm install @babel/preset-env --save-dev
{
"presets": ["@babel/preset-env"]
}

Creating the Model for JSON Output

Once we have the setup finished, lets build out a simple API that returns JSON

Create a models folder with a js file called User.

export default class User {
  constructor(name, username, email){
     this.name = name;
     this.username = username;
     this.email = email;
   }

   getUsername(){
     return this.username;
   }
   getName(){
     return this.name;
   }
}

 

Then create a routes folder with an index.js file.

import express from 'express';
let router = express.Router();
import User from '../models/user';
/* GET home page. */
router.get('/', (req, res, next) => {
   let languages = [
    {
     language: 'Spanish'
    },
    {
     language: "French"
    },
    {
     langauge: "German"
    }
];
res.json(languages);
});
router.get('/users', (req, res, next ) => {
let users = [
new User('James Coonce','jcoonce','none@none.com'),
new User('Bob Coonce','bcoonce','none@none.com'),
new User('Euri','euri','none@none.com'),
new User('Norman','jcoonce','none@none.com'),
];

res.json(users);
});

router.post('/user/create', (req, res) => {
   let user = new User(req.body.name, 
   req.body.username, req.body.email);
   res.json(user);
})

export default router;

 

you can see that we import the express from our node modules and set our router to being the Router method on our imported express class.

We also import the User class and create several instances of it inside of our ‘/users’ and return them as json.

Just to test the post method we also pull in the parameters from the body and return a user object back out as json

let user = new User(req.body.name, req.body.username, req.body.email);
res.json(user);

then finally we export our Router.

As we go back, we create our app.js file

import express from 'express';
import bodyParser from 'body-parser';
import router from './routes/index';
let app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/', router);

app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});

We import express as well as our router and then we add the body parser and router to express and specify which port we want to run on.

To finally wrap things up, we go to our package.json file and write our node script.

nodemon app.js --watch server --exec babel-node

This says run app.js with babel node using the es2015 preset. Now you can go to port localhost:3000 and you should be able to have your application return json at the various urls.

You can find a full example of the github repo here.

Codebrains Newsletter

Get weekly dev news and tutorials.

Powered by ConvertKit