@@ -321,7 +321,7 @@ This is it. For your reference, the front-end app source code is in the `code/08 |
321 | 321 | Message Board API |
322 | 322 | ================= |
323 | 323 |
|
324 | | -The back-end Node.js application source code is at <https://github.com/azat-co/fullstack-javascript/tree/master/code/08-board-api> in the GitHub folder, which has this structure: |
| 324 | +The back-end Node.js application source code is in `code/08-board-api` and at <http://bit.ly/2LbVY84>, which has this structure: |
325 | 325 |
|
326 | 326 | ``` |
327 | 327 | /08-board-api |
@@ -330,9 +330,9 @@ The back-end Node.js application source code is at <https://github.com/azat-co/f |
330 | 330 | -package.json |
331 | 331 | ``` |
332 | 332 |
|
333 | | -The Procfile is for the Heroku deployment, and the `package.json` is for project metadata as well as for Hekoru deployment. |
| 333 | +The `Procfile` file is for the Heroku deployment, and the `package.json` file is for project metadata as well as for Hekoru deployment. |
334 | 334 |
|
335 | | -The `web.js` file is very similar to the `08-board-api-mongo,` but has CORS headers and OPTIONS request handler code. The file starts with importation of dependencies: |
| 335 | +The `web.js` file is very similar to the `08-board-api`, but has CORS headers and OPTIONS request handler code. The file starts with importation of dependencies: |
336 | 336 |
|
337 | 337 | ```js |
338 | 338 | const http = require('http') |
@@ -361,13 +361,13 @@ After we are sure that there were no errors (otherwise the execution flow won't |
361 | 361 | const collection = db.collection('messages') |
362 | 362 | ``` |
363 | 363 |
|
364 | | -The server code follows. We create the server instance and set up the origin variable based on the information from the request. This value will be in the `Access-Control-Allow-Origin`. The idea is that the response will have the value of the client's URL: |
| 364 | +The server code follows. We create the server instance and set up the `origin` variable based on the information from the request. This value will be in the `Access-Control-Allow-Origin` header. The idea is that the response will have the value of the client's URL: |
365 | 365 |
|
366 | 366 | ```js |
367 | 367 | const app = http.createServer(function (request, response) { |
368 | 368 | const origin = (request.headers.origin || '*') |
369 | 369 | ``` |
370 | | -Check for the HTTP method verb. If it's `OPTIONS`, which we must implement for CORS, we start writing headers to the response object: |
| 370 | +Check the HTTP method value in `request.method`. If it's OPTIONS, which we must implement for CORS, we start writing headers to the `response` object: |
371 | 371 |
|
372 | 372 | ```js |
373 | 373 | if (request.method == 'OPTIONS') { |
@@ -387,7 +387,7 @@ The next header will tell what methods are supported: |
387 | 387 | response.end() |
388 | 388 | ``` |
389 | 389 |
|
390 | | -We are done with `OPTIONS`, but we still need to implement `GET` and `POST`: |
| 390 | +We are done with OPTIONS, but we still need to implement GET and POST: |
391 | 391 |
|
392 | 392 | ```js |
393 | 393 | } else if (request.method === 'GET' && request.url === '/messages.json') { |
@@ -430,7 +430,7 @@ We need to parse `data` to get the object so later we can save it into the datab |
430 | 430 | const body = JSON.stringify(obj) |
431 | 431 | ``` |
432 | 432 |
|
433 | | -We add the headers again. Maybe we should write a function and call it instead of writing the headers manually. Wait? Express.js is actually will do some of it for us but it's a topic of [another book](http://proexpressjs.com): |
| 433 | +We add the headers again. Maybe we should write a function and call it instead of writing the headers manually. Wait, Express.js is actually will do some of it for us, but that's a topic for [another book](http://proexpressjs.com) (read my book *Pro Express.js* at <http://amzn.to/1D6qiqk>). The following code supplies the CORS headers for the response: |
434 | 434 |
|
435 | 435 | ```js |
436 | 436 | response.writeHead(200,{ |
@@ -448,7 +448,7 @@ We add the headers again. Maybe we should write a function and call it instead o |
448 | 448 | }) |
449 | 449 | ``` |
450 | 450 |
|
451 | | -Here is a source code of `web.js`, our Node.js application implemented with CORS headers: |
| 451 | +Here is the source code of `web.js`, our Node.js application implemented with CORS headers: |
452 | 452 |
|
453 | 453 | ```js |
454 | 454 | const http = require('http') |
@@ -515,11 +515,9 @@ client.connect(uri, function(error, db) { |
515 | 515 | Deployment to Heroku |
516 | 516 | ==================== |
517 | 517 |
|
518 | | -For your convenience, I placed the front-end app in `code/08-board-ui` and at <http://bit.ly/2LfD1Bo>, and the back-end app with CORS is located in `code/08-board-api` and at <http://bit.ly/2LbVY84>. |
| 518 | +For your convenience, I placed the front-end app in `code/08-board-ui` and at <http://bit.ly/2LfD1Bo>. I also saved the the back-end app with CORS in the `code/08-board-api` folder, and uploaded to <http://bit.ly/2LbVY84>. |
519 | 519 |
|
520 | | -By now, you probably know what to do, but as a reference, below are the steps to deploy these examples to Heroku. |
521 | | -
|
522 | | -We'll start with the API. In the `08-board-api` folder, execute the following code (`$ heroku login` is optional): |
| 520 | +By now, you probably know what to do, but as a reference, below are the steps to deploy these examples to Heroku. We'll start with the API. In the `08-board-api` folder, execute the following code (`$ heroku login` is optional): |
523 | 521 |
|
524 | 522 | $ git init |
525 | 523 | $ git add . |
@@ -529,7 +527,7 @@ We'll start with the API. In the `08-board-api` folder, execute the following co |
529 | 527 | $ heroku addons:create mongolab:sandbox |
530 | 528 | $ git push heroku master |
531 | 529 |
|
532 | | -Watch the terminal messages. If the API is successfully deployed, you can test it with CURL or Postman. Then copy the URL from Heroku (e.g., https://guarded-waters-1780.herokuapp.com), and paste it into the `08-board-ui/app.js` file, assigning the value to the URL variable. Then, in the `08-board-ui` folder, execute: |
| 530 | +Watch the terminal messages. If the API is successfully deployed, you can test it with CURL or Postman. Then copy the URL from Heroku (e.g., https://guarded-waters-1780.herokuapp.com) and paste it into the `code/08-board-ui/app.js` file, assigning the value to the URL variable. Then, in the `code/08-board-ui` folder, execute: |
533 | 531 |
|
534 | 532 | $ git init |
535 | 533 | $ git add . |
@@ -538,21 +536,108 @@ Watch the terminal messages. If the API is successfully deployed, you can test i |
538 | 536 | $ git push heroku master |
539 | 537 | $ heroku open |
540 | 538 |
|
541 | | -That's it. By now you should be able to see Message Board running in the cloud with UI (browser app) on one domain and API on another. In high-trafficked apps, the API will be hiding behind a load balancer so you can have multiple API servers on a single IP/URL. This way they'll handle more traffic and the system will become more resilient. You can take out, restart, or deploy on APIs one at a time with zero down time. |
| 539 | +That's it. By now you should be able to see Message Board running in the cloud with the UI (front-end browser app) on one domain and the API (backend) on another. In high-trafficked apps, the API will be hiding behind a load balancer, so you can have multiple API servers on a single IP/URL. This way they'll handle more traffic and the system will become more resilient. You can take out, restart, or deploy on APIs one at a time with zero downtime. |
542 | 540 |
|
543 | 541 | Same-Domain Deployment Server |
544 | 542 | ============================= |
545 | 543 |
|
546 | | -The same-domain deployment is *not recommended* for serious production applications, because static assets are better served with web servers like Nginx (not Node.js I/O engine), and separating API makes for less complicated testing, increased robustness, and quicker troubleshooting/monitoring. However, the same app/domain approach could be used for staging, testing, development environments, and/or tiny apps. |
| 544 | +The same-domain deployment is *not recommended* for serious production applications, because static assets are better served with web servers like Nginx (not Node.js I/O engine), and separating APIs makes for less complicated testing, increased robustness, and quicker troubleshooting/monitoring. However, the same app/domain approach could be used for staging, testing, development environments, and/or tiny apps. |
547 | 545 |
|
548 | | -The idea is that API serves static files for the browser app as well, not just handling dynamic requests to its routes. So you can copy the `08-board-api` code into a new folder `08-board-web`. The beginning of the new server file is the same; we have GET and POST logic (this time CORS is not needed). The last condition in the chain of `if/else` needs to process the static files. Here's how we can do it. |
| 546 | +The idea is that the API serves static files for the browser app as well, not just handling dynamic requests to its routes. So you can copy the `code/08-board-api` code into a new folder `code/08-board-web` (or getting my copy from GitHub). The beginning of the new server file is the same; we have GET and POST logic (this time CORS is not needed). The last condition in the chain of `if/else` needs to process the static files. Here's how we can do a new response/request handler for static assets: |
549 | 547 |
|
550 | 548 | ```js |
551 | | -... |
552 | | - } else { |
| 549 | +const http = require('http'), |
| 550 | + url = require('url'), |
| 551 | + path = require('path'), |
| 552 | + fs = require('fs'), |
| 553 | + port = process.env.PORT || 1337, |
| 554 | + staticFolder = 'public', |
| 555 | + client = require('mongodb').MongoClient |
| 556 | + |
| 557 | +const uri = process.env.MONGOLAB_URI || 'mongodb://@127.0.0.1:27017/messages' |
| 558 | + |
| 559 | + |
| 560 | +client.connect(uri, function(error, db) { |
| 561 | + if (error) return console.error(error) |
| 562 | + const collection = db.collection('messages') |
| 563 | + |
| 564 | + http.createServer(function(request, response) { |
| 565 | + const origin = (request.headers.origin || '*') |
| 566 | + if (request.method == 'OPTIONS') { |
| 567 | + // ... |
| 568 | + } else if (request.method === 'GET' && request.url === '/messages.json') { |
| 569 | + // ... |
| 570 | + } else if (request.method === 'POST' && request.url === '/messages.json') { |
| 571 | + // ... |
| 572 | + } else { |
| 573 | + const uri = url.parse(request.url).pathname |
| 574 | + console.log('Processing URI: ', uri) |
| 575 | + if (uri == '' || uri == '/') uri = 'index.html' |
| 576 | + filename = path.join(__dirname, staticFolder, uri) |
| 577 | + console.log('Processing file: ', filename) |
| 578 | + try { |
| 579 | + stats = fs.statSync(filename) |
| 580 | + } catch (error) { |
| 581 | + if (error) { |
| 582 | + console.error(error) |
| 583 | + response.writeHead(404, { |
| 584 | + 'Content-Type': 'text/plain'}) |
| 585 | + response.write('404 Not Found\n') |
| 586 | + return response.end() |
| 587 | + } |
| 588 | + } |
| 589 | + if(!stats.isFile()) { |
| 590 | + response.writeHead(404, { |
| 591 | + 'Content-Type': 'text/plain'}) |
| 592 | + response.write('404 Not Found\n') |
| 593 | + return response.end() |
| 594 | + } else { |
| 595 | + const file = fs.readFileSync(filename) |
| 596 | + if (!file) { |
| 597 | + response.writeHead(500, |
| 598 | + {'Content-Type': 'text/plain'}) |
| 599 | + response.write(err + '\n') |
| 600 | + return response.end() |
| 601 | + } |
| 602 | + const extname = path.extname(filename) |
| 603 | + const contentType = 'text/html' |
| 604 | + switch (extname) { |
| 605 | + case '.js': |
| 606 | + contentType = 'text/javascript' |
| 607 | + break |
| 608 | + case '.css': |
| 609 | + contentType = 'text/css' |
| 610 | + break |
| 611 | + case '.json': |
| 612 | + contentType = 'application/json' |
| 613 | + break |
| 614 | + case '.png': |
| 615 | + contentType = 'image/png' |
| 616 | + break |
| 617 | + case '.jpg': |
| 618 | + case '.jpeg': |
| 619 | + contentType = 'image/jpg' |
| 620 | + break |
| 621 | + case '.wav': |
| 622 | + contentType = 'audio/wav' |
| 623 | + break |
| 624 | + } |
| 625 | + response.writeHead(200, { |
| 626 | + 'Content-Type': contentType, |
| 627 | + 'Content-Length': file.length |
| 628 | + }) |
| 629 | + response.end(file) |
| 630 | + } |
| 631 | + } |
| 632 | + }).listen(port) |
| 633 | + |
| 634 | + console.log('Static file server running at\n '+ |
| 635 | + ' => http://localhost:' + port + '/\nCTRL + C to shutdown') |
| 636 | + |
| 637 | +}) |
553 | 638 | ``` |
554 | 639 |
|
555 | | -We use [the url v0.11.0 module](https://github.com/defunctzombie/node-url) from <https://github.com/defunctzombie/node-url> to parse the path name from the URL. The path name is everything after the domain; for example, in <http://webapplog.com/es6> the path name is `/es6`. This will be our folder and file names. |
| 640 | +Let me take you through this implementation line-by-line. We use the `url` module (<https://npmjs.org/url>) to parse the path name from the URL. The path name is everything after the domain; for example, in <http://webapplog.com/es6> the path name is `/es6`. This will be our folder and file names. |
556 | 641 |
|
557 | 642 | ```js |
558 | 643 | const uri = url.parse(request.url).pathname |
@@ -564,7 +649,7 @@ It's good to have some logging to know that our system is working as it should: |
564 | 649 | console.log('Processing path: ', uri) |
565 | 650 | ``` |
566 | 651 |
|
567 | | -The next line deals with the root URI; that is, when you go to the web site and the path is empty or a slash. In this case, let's serve the `index.html` (if it exists): |
| 652 | +The next line deals with the root URI; that is, when you go to the website and the path is empty or a slash, you'll get `index.html`. In our app, let's follow the convention and serve the `index.html` file by default (if it exists): |
568 | 653 |
|
569 | 654 | ```js |
570 | 655 | if (uri == '' || uri == '/') uri = 'index.html' |
@@ -577,7 +662,7 @@ The `path.join()` method will make this code cross-platform by creating a string |
577 | 662 | console.log('Processing file: ', filename) |
578 | 663 | ``` |
579 | 664 |
|
580 | | -I always say never use synchronous functions in Node.js, unless you have to. This is such a case. Without the synch methods, we'll get racing conditions on our files meaning some will load faster than the others and cause conflicts: |
| 665 | +I always say never use synchronous functions in Node.js, unless you have to. This is such a case. Without the synch methods, we'll get racing conditions on our files, meaning some will load faster than the others and cause conflicts: |
581 | 666 |
|
582 | 667 | ```js |
583 | 668 | stats = fs.statSync(filename) |
@@ -617,7 +702,7 @@ Finally, we read the file. We use the synchronous function again for the reasons |
617 | 702 | } |
618 | 703 | ``` |
619 | 704 |
|
620 | | -I know that Douglas Crockford dislikes `switch`, but we'll use it here to determine the right content type for the response header. Most browsers will understand the content type okay if you omit the `Content-Type` header, but why not go an extra mile? |
| 705 | +I know that the JavaScript guru Douglas Crockford dislikes `switch`, but we'll use it here to determine the right content type for the response header. Most browsers will understand the content type okay if you omit the `Content-Type` header, but why not go the extra mile? |
621 | 706 |
|
622 | 707 | ```js |
623 | 708 | const extname = path.extname(filename) |
|