|
3 | 3 | CHAPTER 8 |
4 | 4 | --------- |
5 | 5 |
|
6 | | -Putting It All Together |
| 6 | +Putting Frontend and Backend Together |
7 | 7 | ======================= |
8 | 8 |
|
9 | 9 | > *Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.* |
@@ -12,19 +12,21 @@ Putting It All Together |
12 | 12 |
|
13 | 13 | In this chapter, we'll cover: |
14 | 14 |
|
15 | | -- Adding CORS for Different Domain Deployment |
| 15 | +- Adding CORS for a different-domain deployment |
16 | 16 | - Message Board UI |
17 | 17 | - Message Board API |
18 | 18 | - Deployment to Heroku |
19 | | -- Same Domain Deployment Server |
| 19 | +- Same-domain deployment server |
20 | 20 | - Deployment to Amazon Web Services |
21 | 21 |
|
22 | | -Now, it would be good if we could put our front-end and back-end applications so they could work together. There are a few ways to do it: |
| 22 | +Now, it's a good time to configure our front-end and back-end applications so they could work together. There are a few ways to do it: |
23 | 23 |
|
24 | | -- Different domains (Heroku apps) for front-end and back-end apps: make sure there are no cross-domain issues by using CORS or JSONP. This approach is covered in detail later. |
25 | | -- Same domain deployment: make sure Node.js process static resources and assets for front-end application—not recommended for serious production applications. |
| 24 | +- Different-domain deployment: deploy two separate apps (Heroku apps) for front-end and back-end apps. Developers need to be implement CORS or JSONP to mitigate cross-domain request issues. |
| 25 | +- Same-domain deployment: deploy frontend and backend on the same webapp. Developers need to implement a static Node.js server to serve static assets for the front-end application. This approach is not recommended for serious production applications. |
26 | 26 |
|
27 | | -Adding CORS for Different Domain Deployment |
| 27 | +I cover both approaches in this in detail in this chapter starting with the recommended approach —different-domain deployment. |
| 28 | + |
| 29 | +Adding CORS for Different-Domain Deployment |
28 | 30 | =========================================== |
29 | 31 |
|
30 | 32 | This is, so far, the best practice for the production environment. Back-end applications are usually deployed at the `http://app.` or `http://api.` subdomains. |
@@ -41,30 +43,30 @@ const request = $.ajax({ |
41 | 43 | }) |
42 | 44 | ``` |
43 | 45 |
|
44 | | -The other, and better, way to do it is to add the OPTIONS method, and special headers, which are called [cross-origin resource sharing](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) or CORS (<https://en.wikipedia.org/wiki/Cross-origin_resource_sharing>), to the Node.js server app before the output: |
| 46 | +The other, and better, way to do it is to add the cross-origin resource sharing or CORS support on the server (<https://mzl.la/2LcH9lZ>). It will require to add the OPTIONS method request handler and special headers to other request handlers to the Node.js server app before the output/response. This is a special header that needs to be added to all request handlers. The `origin` is the domain but can be open to anything with `*`: |
45 | 47 |
|
46 | 48 | ```js |
47 | 49 | ... |
48 | 50 | response.writeHead(200,{ |
49 | 51 | 'Access-Control-Allow-Origin': origin, |
50 | | - 'Content-Type':'text/plain', |
51 | | - 'Content-Length':body.length |
| 52 | + 'Content-Type': 'text/plain', |
| 53 | + 'Content-Length': body.length |
52 | 54 | }) |
53 | 55 | ... |
54 | 56 | ``` |
55 | 57 |
|
56 | | -or |
| 58 | +or `origin` value can be locked to only your front-end app location (recommended): |
57 | 59 |
|
58 | 60 | ```js |
59 | 61 | ... |
60 | 62 | res.writeHead(200, { |
61 | | - 'Access-Control-Allow-Origin', 'your-domain-name', |
| 63 | + 'Access-Control-Allow-Origin', 'your-fe-app-domain-name', |
62 | 64 | ... |
63 | 65 | }) |
64 | 66 | ... |
65 | 67 | ``` |
66 | 68 |
|
67 | | -The need for the OPTIONS method is outlined in [HTTP access control (https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS)](https://developer.mozilla.org/en-US/docs/HTTP_access_control). The OPTIONS request can be dealt with in the following manner: |
| 69 | +We need a new response (route or request handler) with the OPTIONS method to tell the client (browser) what methods are supported on the server. The OPTIONS request can be implemented in the following manner: |
68 | 70 |
|
69 | 71 | ```js |
70 | 72 | ... |
@@ -74,7 +76,7 @@ The need for the OPTIONS method is outlined in [HTTP access control (https://dev |
74 | 76 | "Access-Control-Allow-Methods": |
75 | 77 | "GET, POST, PUT, DELETE, OPTIONS", |
76 | 78 | "Access-Control-Allow-Headers": "content-type, accept", |
77 | | - "Access-Control-Max-Age": 10, // Seconds. |
| 79 | + "Access-Control-Max-Age": 10, // In seconds |
78 | 80 | "Content-Length": 0 |
79 | 81 | }) |
80 | 82 | response.end(); |
@@ -85,16 +87,16 @@ The need for the OPTIONS method is outlined in [HTTP access control (https://dev |
85 | 87 | Message Board UI |
86 | 88 | ================ |
87 | 89 |
|
88 | | -Our front-end application used Parse.com as a replacement for a back-end application. Now we can switch to our own back end replacing the endpoints along with a few other painless changes. Let me walk you through them. |
| 90 | +Our front-end application used Parse.com as a replacement for a back-end application. Now we can switch to our own backend by replacing the endpoints along with making a few other painless changes. Let me walk you through them. |
89 | 91 |
|
90 | | -In the beginning of the `app.js` file, uncomment the first line for running locally, or replace the URL values with your Heroku or Windows Azure back-end application public URLs: |
| 92 | +In the beginning of the `app.js` file, uncomment the first line for running locally, or replace the URL values with your Heroku or Microsoft Azure back-end application public URLs: |
91 | 93 |
|
92 | 94 | ```js |
93 | 95 | // const URL = 'http://localhost:1337/' |
94 | 96 | const URL ='http://your-app-name.herokuapp.com/' |
95 | 97 | ``` |
96 | 98 |
|
97 | | -Most of the code in `app.js` and the folder structure remained intact from the `06-board-backbone-parse-sdk` project, with the exception of replacing Parse.com models and collections with original Backbone.js ones. So go ahead and type or copy the RequireJS block for loading of the dependencies (templates in this case): |
| 99 | +Most of the code in `app.js` and the folder structure remained intact from the `code/05-board-backbone-parse-sdk` project (<http://bit.ly/2LfB9IQ>), with the exception of replacing Parse models and collections with original Backbone.js ones. So go ahead and type or copy the RequireJS block for loading of the dependencies (templates in this case): |
98 | 100 |
|
99 | 101 | ```js |
100 | 102 | require([ |
@@ -107,9 +109,9 @@ require([ |
107 | 109 | footerTpl) { |
108 | 110 | ``` |
109 | 111 |
|
110 | | -The `ApplicationRouter`, `HeaderView``,` and `FooterView` are the same as in the `06-board-backbone-parse-sdk` project so I won't list them here again. |
| 112 | +The `ApplicationRouter`, `HeaderView,` and `FooterView` are the same as in the `code/05-board-backbone-parse-sdk` project so I won't list them here again. |
111 | 113 |
|
112 | | -We need to change the the model and collection to this from using `Parse.Object` and `Parse.Collection`. Those are the places where Backbone.js looks up for REST API URLs corresponding to the specific collection and model: |
| 114 | +We need to change the model and collection to this from using `Parse.Object` and `Parse.Collection`. Those are the places where Backbone.js looks up for REST API URLs corresponding to the specific collection and model: |
113 | 115 |
|
114 | 116 | ```js |
115 | 117 | Message = Backbone.Model.extend({ |
@@ -132,22 +134,24 @@ Next is the `HomeView` where most of the logic resides. I made a few enhancement |
132 | 134 | }, |
133 | 135 | ``` |
134 | 136 |
|
135 | | -Now, in the constructor of the view set the `homeView` to `this` so we can use `this` later by the name inside of the closures (otherwise, `this` can mutate inside of the closures): |
| 137 | +Now, in the constructor of the view, set the `homeView` to `this` so we can use `this` later by the name inside of the callbacks/closures or use fat arrow functions `()=>{}` (otherwise, `this` can mutate inside of the callbacks/closures): |
136 | 138 |
|
137 | 139 | ```js |
138 | 140 | initialize: function() { |
139 | 141 | const homeView = this |
140 | 142 | ``` |
141 | 143 |
|
142 | | -Then, I attached an event listener `refresh` that will do the rendering. Prior to that we had the `all` event, which wasn't very good, because it triggered re-rendering the addition of each message. You see, `fetch` will trigger `add` as many times as there are messages (10, 100, 1000, etc.) and if we use `all` event listener, `add` is part of `all`. While with this custom event `refresh` we can trigger rendering in the appropriate places (you'll see them later). |
| 144 | +Next, I attach an event listener `refresh` that will do the rendering. Prior to that we had the `all` event, which wasn't very good, because it triggered re-rendering multiple times on the addition of each message. The reason is that `fetch()` triggers `add()` as many times as there are messages (10, 100, 1000, etc.). So if we use the `all` event listener for `render()`, our app will unnecessarily render multiple times. A better way is to use a custom event `refresh` that we will trigger manually and only in the appropriate places (you'll see them later). This will prevent multiple re-rendering. |
| 145 | +
|
| 146 | +The following code creates the collection, creates the `refresh` event and starts the `fetch` request to populate the messages from the backend: |
143 | 147 |
|
144 | 148 | ```js |
145 | 149 | homeView.collection = new MessageBoard() |
146 | 150 | homeView.collection.bind('refresh', homeView.render, homeView) |
147 | 151 | homeView.collection.fetch({ |
148 | 152 | ``` |
149 | 153 |
|
150 | | -The `fetch` method will perform GET XHR request and it has `success` and `error` callbacks (indentation removed): |
| 154 | +The `fetch` method will perform a GET XHR request, and it has `success` and `error` callbacks (indentation removed): |
151 | 155 |
|
152 | 156 | ```js |
153 | 157 | success: function(collection, response, options){ |
@@ -165,7 +169,7 @@ The next line will trigger rendering only after all the messages are in the coll |
165 | 169 | }) |
166 | 170 | ``` |
167 | 171 |
|
168 | | -This event listener will be triggered by the SEND button as well as by the `fetch`. To avoid persisting existing records with `message.save()`, we add the check for the `message.attributes._id`. In other words, if this an existing message and it comes from the server (`fetch`), then it will have `_id` and we stop the execution flow. Otherwise, we persist the message and trigger rendering on success: |
| 172 | +This event listener will be triggered by the "SEND" button as well as by the `fetch`(). To avoid persisting existing records with `message.save()`, we add the check for the `message.attributes._id`. In other words, if this is an existing message and it comes from the server (`fetch`), then it will have `_id` and we stop the execution flow. Otherwise, we persist the message and trigger rendering on success: |
169 | 173 |
|
170 | 174 | ```js |
171 | 175 | homeView.collection.on('add', function(message) { |
@@ -183,7 +187,7 @@ This event listener will be triggered by the SEND button as well as by the `fetc |
183 | 187 | }, |
184 | 188 | ``` |
185 | 189 |
|
186 | | -The rest of the `HomeView` object is the same as in the `06-board-parse-sdk` project. In the `saveMessage` we get the values of the username and the message text and add the new message object to the collection with `collection.add()`. This will call the event listener `add`, which we implemented in the `initialize`. |
| 190 | +The rest of the `HomeView` object is the same as in the `05-board-parse-sdk` project. In the `saveMessage` we get the values of the username and the message text and add the new message object to the collection with `collection.add()`. This will call the event listener `add`, which we implemented in the `initialize`. |
187 | 191 |
|
188 | 192 | ```js |
189 | 193 | saveMessage: function(){ |
@@ -211,8 +215,7 @@ Last, we write or copy the `render` method that takes the template and the colle |
211 | 215 | }) |
212 | 216 | ``` |
213 | 217 |
|
214 | | -Here is the full source code of the [08-board-ui/app.js](https://github.com/azat-co/fullstack-javascript/blob/master/code/08-board-ui/app.js) |
215 | | -file (https://github.com/azat-co/fullstack-javascript/blob/master/code/08-board-ui/app.js): |
| 218 | +Here is the full source code of the `code/08-board-ui/app.js` file (<http://bit.ly/2LaHhCp>): |
216 | 219 |
|
217 | 220 | ```js |
218 | 221 | const URL = 'http://localhost:1337/' |
@@ -313,7 +316,7 @@ require([ |
313 | 316 | }) |
314 | 317 | ``` |
315 | 318 |
|
316 | | -This is it. For your reference, the front-end app source code is at [https://github.com/azat-co/fullstack-javascript/tree/master/code/08-board-u](https://github.com/azat-co/fullstack-javascript/tree/master/code/08-board-ui) in the GitHub folder. I won't list it here because we had only a few changes comparing with the Parse SDK project. The next piece of the puzzle is the back end. |
| 319 | +This is it. For your reference, the front-end app source code is in the `code/08-board-ui` folder and on GitHub at <http://bit.ly/2LfD1Bo>. I won't list it here because we had only a few changes comparing with the Parse SDK project. The next piece of the puzzle is the backend. |
317 | 320 |
|
318 | 321 | Message Board API |
319 | 322 | ================= |
|