Code Monkey home page Code Monkey logo

express-workshop's Introduction

Introduction to Node and Express Workshop

Starter Code Includes

  • Babel Express Server
  • Eslint with airbnb config

What We Will Be Building

A quote board site with the ability to

  1. Create a Quote
  2. Delete a Quote

What are Node.js and Express?

Node.js is a Javascript environment that allows us to run the language outside of the browser. Javascript is an asynchronous, non-blocking, event driving, language. This model allows JavaScript to manage multiple requests/users in a performant manner and hence makes it an invaluable language for client and server-side web development.

Express.js offers us routing via middleware. Middleware functions act on user request and can pass them along. This pattern makes express middleware functions composable and reduces the need for repeated code.

Getting Started

Installation

I recommend using Node Version Manager or nvm to install node.

Mac

$ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh | bash
$ nvm install node

Windows

Go to the node and click install node 7.

We also need to install mongodb

Starter Code

  1. Create a fork of: https://github.com/RcrsvSquid/express-workshop
  2. Clone your fork
$ git clone <YOUR_FORK_URL>
$ cd <YOUR_NEW_REPO>

Install the dependencies with npm

NPM stands for Node Package Manager. NPM creates a package.json file which lists all the dependencies needed to build and run your project.

In your repository

$ npm install

Other npm commands include:

$ npm init # creates initializes a package
$ npm install --save <PACKAGE> # downloads and saves a package to the package.json file
$ npm install --save-dev <PACKAGE> # saves the package as a development dependency

Aside: yarn is a new package manager that is gaining popularity.

Up and running

The package.json file contains a few scripts to get started.

Scripts

$ npm run dev # runs the server in reloading mode using nodemon
$ npm run start # runs the server with babel
$ npm run build # transpiles the server for production use
$ npm run prod # builds and runs the server for production use

Run the server!

$ npm run dev

then open your browser to http://localhost:9090 You should see a blank quote board:

Quote Blank

Express

Open up app/server.js. This is where the configuration for our app lives. You'll notice on line 32 that we have connected routes to our app.

Lets take a deeper look. Open up app/router.js.

The anatomy of an express route

app.get('/:name', (req, res, next) => {
	const name = req.params.name;

	res.json({ message: `Hello name ${name}`});
});

CRUD

  • Create
  • Read
  • Update
  • Delete

In the interest of time we will be implementing create and delete.

Create

There is a form created for you. Click the link in the top right corner of the webpage.

For this to work we need a corresponding post on the backend to save our data to the database. I have already hooked up the route on the backend but the handling logic needs to be completed.

First to verify that the route is working by running a curl command.

$ curl -X POST -H "Content-Type: application/json" -d '{
	"text": "This is a test quote",
	"author": "me"
}' "http://localhost:9090/api/posts"

If you reload the page you should see your test post.

Let's implement the createQuote route handler in app/controllers/quote.js

const newQuote = new Quote(req.body);

newQuote.save()
  .then((post) => {
    res.json({ message: 'post created' });
  })
  .catch((error) => { next(error); });

Delete

We need to find the corresponding quote and remove it. We need to grab the id off of params as discussed earlier in order to do this.

  Quote.findById(req.params.id)
    .then((post) => post.remove()) // eslint-disable-line
    .then(() => { res.sendStatus(200); })
    .catch((error) => { next(error); });

Error handling in Express

An express middleware function that takes 4 paramaters can handle errors. We can do this centrally and I have included an example in app/server.js

Since we have a catch all error handler we can use next(err) when errors arrise in our routes.

express-workshop's People

Contributors

sidneyw avatar timofei7 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.