![](https://img.shields.io/badge/status-review-orange.svg) > This class is based on the [Node Girls Express Workshop](https://github.com/node-girls/express-workshop) # Express Workshop Fork the [express-workshop repository](https://github.com/CodeYourFuture/express-workshop) ```sh git clone https://github.com/YOUR-USERNAME/express-workshop ``` # Step 1 - Setting up your project When creating a Node.js project, you will be installing a lot of different things along the way. If you want to share your project with others, you need to have a list of the things you installed, so that other people know what to install in order to run the project. In Node.js, this 'list' file is called a `package.json`. The 'things you've installed' are referred to as **dependencies**. Creating this file is the first step in setting up your Node.js project. ## 1. Make a `package.json` file Let's start by creating the `package.json` file. We can add things to it as the project grows. The `package.json` file is easy to create from the command line. Type the following command into your terminal to get started: ```sh $ npm init ``` This command will initialise a step-by-step process for creating the `package.json`. You should see something like this: ![starting npm init](https://raw.githubusercontent.com/node-girls/workshop-cms/master/readme-images/step1-npm-init01.png) It will ask you a bunch of questions. > You can skip most of the questions but change the `entry point` from > `(index.js)` to `server.js`. > The wizard asks you for the following information: `name`, `version`, > `description`, `main`, `test`, `repository`, `keywords`, `author`, `license` - > do you understand all of them? At the endo of the wizard, you should see a new file called `package.json` in your project's folder. Here is an example `package.json` file for a project called [Passport](https://github.com/jaredhanson/passport/blob/master/package.json). # What is JSON? JSON is a type of file for structuring data in a readable way. It is also a really popular format for sending data across the web. JSON is a string representation of a Javascript object. JSON objects convert really easily to Javascript objects, and vice versa, with `JSON.parse()` and `JSON.stringify()`. ```js { "firstName": "John", "lastName": "Smith", "isAlive": true, "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021-3100" }, "phoneNumbers": [ { "type": "home", "number": "212 555-1234" }, { "type": "office", "number": "646 555-4567" }, { "type": "mobile", "number": "123 456-7890" } ], "children": [], "spouse": null } ``` # Step 2 - Installing Express Before we write any code, you'll need to install the Express library. We're going to use the **[Node Package Manager (npm)](https://www.npmjs.com/)** to download it using the **`npm install`** command. NPM is the place to go to download other Node code written by other people. There are thousands of open-source, 3rd-party Node modules (also known as "packages") by other people that you can download and use in your own projects. As we install Express, we'll need to update the `package.json` to add Express as a dependency. We do this so that other people working on the project will know to install Express before running any of the code. This can be done by adding **`--save`** to the end of your command. Run the following command in your terminal: ```sh npm install express --save ``` Express should now be installed. Check your `package.json` file to make sure it has been added as a dependency. It will look like this: ![package.json screenshot](https://cloud.githubusercontent.com/assets/10683087/16382664/be35f0b4-3c79-11e6-82b6-ae9e4a037c3f.png) # Step 3 - Building the server The first thing we need to do is build our server. You will always need to build a server when writing back-end code. A server can be built in pure Node.js, but Express gives us simpler syntax to work with. ## 1. Create a `server.js` file Let's build our server! Before we do anything, let's create a new file called `server.js`. This is where all our server code is going to live. ## 2. `require` the `express` library We already installed Express in Step 2, but we need to make sure it is included in this file specifically so we can make use of its methods. In Node.js, when you want to access the functionality of a library or module in another file, you `require` it. To import Express, write the following inside `server.js`: ```js const express = require("express"); ``` > We will try and get used to ES6 syntax - so use `const` and `let` instead of > `var`. ## 3. Initialise the server To initialise our server, we just need to call the `express()` function. This will create an Express application for us to work with. Add the second line of code to your `server.js` file: ```js const express = require("express"); const app = express(); ``` ## 4. Start 'listening' for potential requests One more step left, we need to set a **port** for our server to listen to. Think of a port as a door number; any requests that come to the server will come via that door. Setting a port will allow us to find where our server is running. We use the **`app.listen`** method to do this. This method takes two arguments: a **port** and a **callback function** telling it what to do once the server is running. Need clarification? Read more about the `app.listen` method in the [Express documentation](http://expressjs.com/en/4x/api.html#app.listen). We're going to run our server on port `3000`, and run a simple `console.log` as our callback function. Update your `server.js` file, calling the `app.listen` method: ```js const express = require("express"); const app = express(); app.listen(3000, function() { console.log("Server is listening on port 3000. Ready to accept requests!"); }); ``` > Try to use ES6 arrow functions instead of `function`. ## 5. Switch the server on! You've built your server, but it isn't running yet. We need to run a command in the terminal to do this. We are going to use the `node` keyword to run the server file. Type the following command in your terminal: ```sh node server.js ``` If you see this, congratulations! You have built yourself a server! ![success](https://raw.githubusercontent.com/node-girls/workshop-cms/master/readme-images/step2-server02.png) # Step 4 - Communicating with the server Now that we've built the server, we need to communicate with it. We're going to control the server with **handler functions**. ### What is a handler function? When a request reaches the server, we need a way of responding to it. In comes the handler function. The handler function is just a function which receives requests and handles them, hence the name. The handler function always takes a `request` and `response` object, and sends the response back to the client along with some information. You can decide what to send back in your response. ### What does a handler function look like in Express? The `get()` [method](http://expressjs.com/en/api.html#app.get.method) is used to define a handler function in Express. It takes two parameters: the **endpoint** at which to trigger an action (we'll explain more about this in the next step), and the handler function that tells it exactly what to do. Here's a simple "Hello World!" example: ```js // req is the Request object, res is the Response object // (these are just variable names, they can be anything but it's a convention to call them req and res) app.get("/", function(req, res) { res.send("Hello World!"); }); ``` Here, we are telling our server to respond with "Hello World!" when someone tries to access the webpage. ## 1. Create your own handler function. We are now making a handler function with a custom message in our response. You can write any message you want. Update your `server.js` file with an empty `app.get()` function: ```js const express = require("express"); const app = express(); app.get("/", function(req, res) {}); app.listen(3000, function() { console.log("Server is listening on port 3000. Ready to accept requests!"); }); ``` > Exercise: Try to `console.log` the `request` object inside the handler > function. Restart your server, refresh the browser, then go to your terminal > to see what it looks like. You should see a lot of data come through. ## 2. Tell your handler function what to do We want our handler function to send back a message to the client. To do that, we're going to use the Express `send()` [method](http://expressjs.com/en/api.html#res.send). This will update the response object with the message. Update your handler function like so: ```js const express = require("express"); const app = express(); app.get("/", function(req, res) { res.send("Yay Node Girls!"); }); app.listen(3000, function() { console.log("Server is listening on port 3000. Ready to accept requests!"); }); ``` ## 3. Check it out in your browser Quit your server in the terminal with `ctrl + c`. Then restart it to run your new changes. ```sh node server.js ``` Now, open your favourite browser (we like Chrome), and navigate to `http://localhost:3000`. If you see your message in the browser, congratulations! You just sent your first response from the server. # Step 5 - Routing At the moment our server only does one thing. When it receives a request from the `/` endpoint, it sends back the same response: "Yay Node Girls!". > Try typing http://localhost:3000/nodegirls and see what happens. However by making use of endpoints, we can make the server send different responses for different requests. This concept is called **routing**. ### What is an endpoint? An endpoint is the part of the URL which comes after `/`. For example: `/chocolate` is the "chocolate" endpoint. It's the URL to which you send a request. ### What is URL? ![alt text](https://github.com/CodeYourFuture/syllabus/blob/scotland/node-db/http1-url-structure.png "URL") ## 1. Create your own endpoints and send different responses We're going to try sending different responses at different endpoints. Remember the `app.get()` method? To set up routing in your server, we just need to repeat this method with different endpoints. For example: ```js app.get("/", function(req, res) { res.send("Hello World!"); }); app.get("/chocolate", function(req, res) { res.send("Mm chocolate :O"); }); ``` > **Exercise:** Add some code so that your server sends one message when the > endpoint is `/node` and another one when it's `/girls`. ### Step 6 - Serving static files So we know how to send back a simple message. But what if you want to send back a whole HTML page, or an image? Things like HTML files, images etc are known as **static assets**. If you want your server to "serve" static assets back to the browser, you need to do something different than just using the `res.send()` method. To be able to send any file from the server we need a special, built-in **middleware** function that comes with Express: `express.static()`. Read more about it [here](http://expressjs.com/en/starter/static-files.html). Say we want to serve all the static assets in our "public" folder. The `express.static()` function will look like this: ```js app.use(express.static("public")); ``` ## 1. Serve static files from your server Delete all your `app.get` endpoint functions, and replace them with the line of code above. Restart your server, refresh your browser and see what happens! If you see a Node Girls CMS, then your static assets have been successfully served. ### HTTP request methods All requests use one of the `HTTP methods`. The main ones are: `GET, POST, PUT, DELETE`. `app.get` deals with requests that use the `GET` HTTP method. > We will go into these Methods into more details, but for now, think of `GET` > as a method for Getting data. `POST` is for POSTing/inserting new data. `PUT` > is for updating. `DELETE` is for deleting data. ### The `POST` http request method When sending data to the server, we use the `POST` http request method, instead of `GET`. Let's try `POST`ing some text to the server. We're going to add a form to the `index.html` page, so that you can write your blogposts from there. Open up the `index.html` file in your text editor. If you have a look, you should see this: ```html