GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — add changes :file_folder: · gokulcoder7/fullstack-javascript@2e83550

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • chapter8
    • chapter8.md
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎chapter8/chapter8.md‎

Copy file name to clipboardExpand all lines: chapter8/chapter8.md
+107-22Lines changed: 107 additions & 22 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,7 @@ This is it. For your reference, the front-end app source code is in the `code/08
321321
Message Board API
322322
=================
323323
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:
325325
326326
```
327327
/08-board-api
@@ -330,9 +330,9 @@ The back-end Node.js application source code is at <https://github.com/azat-co/f
330330
-package.json
331331
```
332332
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.
334334
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:
336336
337337
```js
338338
const http = require('http')
@@ -361,13 +361,13 @@ After we are sure that there were no errors (otherwise the execution flow won't
361361
const collection = db.collection('messages')
362362
```
363363
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:
365365
366366
```js
367367
const app = http.createServer(function (request, response) {
368368
const origin = (request.headers.origin || '*')
369369
```
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:
371371
372372
```js
373373
if (request.method == 'OPTIONS') {
@@ -387,7 +387,7 @@ The next header will tell what methods are supported:
387387
response.end()
388388
```
389389
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:
391391
392392
```js
393393
} 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
430430
const body = JSON.stringify(obj)
431431
```
432432
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:
434434
435435
```js
436436
response.writeHead(200,{
@@ -448,7 +448,7 @@ We add the headers again. Maybe we should write a function and call it instead o
448448
})
449449
```
450450
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:
452452
453453
```js
454454
const http = require('http')
@@ -515,11 +515,9 @@ client.connect(uri, function(error, db) {
515515
Deployment to Heroku
516516
====================
517517
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>.
519519
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):
523521
524522
$ git init
525523
$ git add .
@@ -529,7 +527,7 @@ We'll start with the API. In the `08-board-api` folder, execute the following co
529527
$ heroku addons:create mongolab:sandbox
530528
$ git push heroku master
531529
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:
533531
534532
$ git init
535533
$ git add .
@@ -538,21 +536,108 @@ Watch the terminal messages. If the API is successfully deployed, you can test i
538536
$ git push heroku master
539537
$ heroku open
540538
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.
542540
543541
Same-Domain Deployment Server
544542
=============================
545543
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.
547545
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:
549547
550548
```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+
//MONGOLAB_URI=mongodb://user:[email protected]:port/db_name
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+
})
553638
```
554639
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.
556641
557642
```js
558643
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:
564649
console.log('Processing path: ', uri)
565650
```
566651
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):
568653
569654
```js
570655
if (uri == '' || uri == '/') uri = 'index.html'
@@ -577,7 +662,7 @@ The `path.join()` method will make this code cross-platform by creating a string
577662
console.log('Processing file: ', filename)
578663
```
579664
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:
581666
582667
```js
583668
stats = fs.statSync(filename)
@@ -617,7 +702,7 @@ Finally, we read the file. We use the synchronous function again for the reasons
617702
}
618703
```
619704
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?
621706

622707
```js
623708
const extname = path.extname(filename)

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.