Giter VIP home page Giter VIP logo

web-development-with-node-and-express's Introduction

Web Development With Node And Express

This is the companion repository to Web Development With Node and Express, 1st Edition. With this repository, you can follow along with any of the code samples in the book, as well as see additional material that wasn't appropriate for the book format.

IMPORTANT: New Structure

The first version of the book attempted to treat the repo as a linear development effort. That is, it attempted to mirror the progress a reader might make as he or she went through the book...or the progress a real development effort might take. This approach was well-intentioned, but turned out to cause more problems than it solved. After struggling with those problems, I realized that compromises had to be made to reflect the reality of this repo (including the amount of time I have to maintain this repo). Instead of a linear commit history with tags for each chapter, each chapter now lives in its own directory (including an "alternate ending" chapter, ch-08-jquery-file-upload). Tags now represent "versions". The nice thing about versions is that the version of the book you're reading can be correlated to the version of the repository. For example, if your book says to use version 1.5, you can checkout tag 1.5, and feel confident that the code will mirror what you're reading.

Benefits of this approach:

  • Code samples match what's in the book (see "If You're Following Along by Using the Official Repository" in Chapter 4 for the version number).
  • Reduced maintenance for me. This is good for you because it allows me to focus on making meaningful updates to the book.
  • Easier to accept community contributions. This makes it a lot easier for me to accept community contributions. I can see quickly and easily what chapter(s) you're correcting, and correct the book in parallel.

Code in the book not working?

After checking for typos, try the following steps:

  • Select the folder that corresponds to the book chapter (e.g. Chapter 5) and compare your package.json to the one in this repo. To rule out problems related to package versions try reinstalling the packages to match the specific version specified in the most current package.json. To do so, run npm install with the specific package version (e.g. npm install --save [email protected]).
  • Still within the chapter folder, click on the text latest commit on the right side of the window to see the newest changes to the code in this chapter => a red background means that the code was deleted and you should delete it too. A green background means that this is new code that was added and, likewise, you should add it. To reiterate the previous section: beyond the specific version tag that matches your copy of the book (1.5.1, for example) you may see code changes that don't match.

Contributing

I am happy to accept PRs for this repository, for changes big and small. Please keep in mind, however, that changes to the repository have to be kept in sync with changes in the book. Any work you can do in your PR to make it clear to me what changes need to be made in the book is very helpful to me. Before sending a PR, please consider the following:

  • If you're just correcting typos or minor things, I prefer one big PR with lots of typo corrections to a bunch of small PRs with corrections.
  • If you're suggesting major changes to code that appears in the book, I recommend you discuss it with me first. I would hate for you to do a lot of work that I am unable or unwilling to sync with the book.
  • While not every bit of code is carried from chapter to chapter, most of it is. If you make code changes in ch05, make sure you make the same changes in ch06 to ch19. This is one of the first things I'll check in your PR.

This Repo Doesn't Contain Everything You Need

Many of the questions I receive have to do with the chapter sample code not working "out of the box." Most of these are because the reader hasn't taken note that you have to create your own credentials.js file. The sample project relies on a lot of third-party services: Twitter, Google, MongoLabs, Weather Underground, etc. Not only do I not wish to share my personal access tokens for these sites, it would be against the terms of service for those sites. The book has instructions for creating your own credentials.js and attaching to the appropriate account(s) you'll need. This important file doesn't show up until ch09, so if you just want to get something up and running without any work, try one of the early chapters. Starting with ch09, you've got to do a little work yourself to get the site running.

What Happened to the Original Code?

The original master branch that I developed for the first version of the book has been saved as the legacy branch. Please do NOT do any development on this branch; it is only there for reference. I will NOT consider any PRs from this branch.

web-development-with-node-and-express's People

Contributors

anemochore avatar bgazzera avatar chadfawcett avatar ethanrbrown avatar eveness avatar gh0st avatar iobregon avatar micahpowell avatar natejlee avatar zhtubo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

web-development-with-node-and-express's Issues

git checkout ch17


the js files don't start with: (function(){
'use strict';
}());


1)- server can't start missing "credentials.js"

2)- node.js complains:
express-session deprecated undefined resave option; provide resave option meadowlark.js:100:35
express-session deprecated undefined saveUninitialized option; provide saveUninitialized option meadowlark.js:100:35
express-session deprecated req.secret; provide secret option meadowlark.js:100:35
body-parser deprecated bodyParser: use individual json/urlencoded middlewares meadowlark.js:102:31
body-parser deprecated undefined extended: provide extended option node_modules/body-parser/index.js:85:29

3)- Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:689:11)
at ServerResponse.res.setHeader (/home/douglas/workspace/web-development-with-node-and-express/git checkout ch17/node_modules/connect/lib/patch.js:134:22)

4)- GET /css/main.css 404 222.462 ms - 2979
GET /css/cart.css 404 148.158 ms - 2979

5)- at ServerResponse.res.setHeader (/home/douglas/workspace/web-development-with-node-and-express/git checkout ch17/node_modules/connect/lib/patch.js:134:22)

Chapter 5: Mocha and Chai Cross-Page Testing Issue

Hi, Ethan

I am really enjoying your book.
Great work!

I have written the code myself and I also have checked out your repo(ch07 tag).
I have a problem with cross page testing.
The first test always fails.
Please see the screen shot.

screen shot 2014-11-28 at 10 01 14 am

Not able to use ch04 tag

Hi,

I have cloned this repository, and as mentioned in book, was trying to checkout ch04. But not able to .
Is the tags defined ?

Thanks,
arbarik

Chapter 07 - Uncaught ReferenceError: Handlebars is not defined

Hi Ethan. I can't get the nursery rhyme examples in Chapter 7 to work. Line 23 in nursery-rhyme.handlebars causes the error: Uncaught ReferenceError: Handlebars is not defined

Line 23:
var nurseryRhymeTemplate = Handlebars.compile($('#nurseryRhymeTemplate').html());

Any suggestions?

un-necessary commas

1)- the last entry within an object ( key-value pairs) ends with a comma
in all the code. Thus Causing the speckling of the gutter with red marks
within the ide.
2)- require(); has Many ' ' omissions surrounding the parameter,

3)- package.json seems out of date

[email protected] node_modules/grunt/node_modules/grunt-legacy-log/node_modules/colors
npm WARN unmet dependency /home/douglas/workspace/web-development-with-node-and-express/git checkout ch17/node_modules/connect requires body-parser@'~1.9.3' but will load
npm WARN unmet dependency /home/douglas/workspace/web-development-with-node-and-express/git checkout ch17/node_modules/body-parser,
npm WARN unmet dependency which is version 1.3.1
npm WARN unmet dependency /home/douglas/workspace/web-development-with-node-and-express/git checkout ch17/node_modules/connect requires morgan@'~1.4.1' but will load
npm WARN unmet dependency /home/douglas/workspace/web-development-with-node-and-express/git checkout ch17/node_modules/morgan,
npm WARN unmet dependency which is version 1.1.1
npm WARN unmet dependency /home/douglas/workspace/web-development-with-node-and-express/git checkout ch17/node_modules/connect requires vhost@'~3.0.0' but will load
npm WARN unmet dependency /home/douglas/workspace/web-development-with-node-and-express/git checkout ch17/node_modules/vhost,
npm WARN unmet dependency which is version 2.0.0
npm WARN unmet dependency /home/douglas/workspace/web-development-with-node-and-express/git checkout ch17/node_modules/express-logger requires express@'2.5.9' but will load
npm WARN unmet dependency /home/douglas/workspace/web-development-with-node-and-express/git checkout ch17/node_modules/express,
npm WARN unmet dependency which is version 4.4.5
npm WARN unmet dependency /home/douglas/workspace/web-development-with-node-and-express/git checkout ch17/node_modules/grunt/node_modules/findup-sync requires glob@'~3.2.9' but will load
npm WARN unmet dependency /home/douglas/workspace/web-development-with-node-and-express/git checkout ch17/node_modules/grunt/node_modules/glob,
npm WARN unmet dependency which is version 3.1.21
npm WARN unmet dependency /home/douglas/workspace/web-development-with-node-and-express/git checkout ch17/node_modules/grunt/node_modules/findup-sync requires lodash@'~2.4.1' but will load
npm WARN unmet dependency undefined,
npm WARN unmet dependency which is version undefined
npm WARN engine [email protected]: wanted: {"node":">= 0.4.1 < 0.7.0"} (current: {"node":"0.10.32","npm":"1.4.28"})
npm WARN engine [email protected]: wanted: {"node":">= 0.11.12"} (current: {"node":"0.10.32","npm":"1.4.28"})

Typo in Readme

You have structure spelled as Strucutre in the headings.

domain.on('error', ...) not called

Given a route defined as:

app.get('/error', function(req, res) {
  throw new Error('Testing');
});

When requested, the error event is not emitted.

Thoughts?

The completed sample is required to operate at Heroku server hosting

I would appreciate if you fill this function below ..

Chapter 8 and Chapter 13:
function saveContestEntry(contestName, email, year, month, photoPath){
// TODO...this will come later
}

The completed sample is required to operate at Heroku server hosting
because of the following error

Error: EXDEV: cross-device link not permitted, rename '/tmp/upload_f8c7f27f5fc96f1455e35cb30e2c7399' -> '/app/uploads/property/photo/1453171290731/์‚ฌ๋‹นํœด๋ธŒ๋ฆฌ์ง€์˜คํ”ผ์Šคํ…”๊ฒ€์ƒ‰๊ฒฐ๊ณผ.jpg'

And
i would like to done my first sample works..
http://helloslow.herokuapp.com/

Ch 5. Missing dependencies in the test files with Grunt Setup?

I made the shift over to the grunt setup at the end of chapter 5. However, when I ran 'grunt' a few errors occurred.

Two of the tests, 'public/qa/tests-about.js' and 'public/qa/tests-global' were erroring out saying that 'assert' was not defined. So, I added in chai's assert via require, and then ran 'grunt' again.

For the tests-about.js file, now it was showing that '$' was not defined. So I found the jQuery npm module and after installing used the require to bring that in. However, after that it said that undefined was not a function.

For the tests-global, it said 'document is not defined'. So I did a little searching and thought possibly that I needed to bring in jsdom. I gave that a go but after running grunt it came back with 'Unspecified AssertionError'.

Any ideas? Thanks a lot!

Chapter 5: Functional Testing Errors

Hey Ethan,

First want to say that I'm really enjoying working through your book. I've wanted to learn Node and Express for awhile, I this is the right book for me.

However, I'm having some issues with the Cross-page tests in Chapter 5. I've seen a few people post about these tests, but I haven't been able to find out what I'm doing wrong. I've been poring over the docs for Zombie, but they've failed to spotlight the problem so far.

I'm receiving this error for both the hood-river and oregon-coast tests. It looks like browser.field('referrer').value is returning null and I can't figure out why. I've been stuck on this for a bit and I may just skip it for now, but I thought I'd reach out.

Thanks.

Error

1) Cross-Page Tests requesting a group rate quote from the hood river tour page should populate the hidden referrer field correctly:
     Uncaught AssertionError: Unspecified AssertionError
      at qa/tests-crosspage.js:17:5
      at EventLoop.done (node_modules/zombie/lib/eventloop.js:589:11)
      at Immediate._onImmediate (node_modules/zombie/lib/eventloop.js:688:71)

Relevant views

<h1>Hood River Tour</h1>
<a class="requestGroupRate" href="/tours/request-group-rate">Request Group Rate.</a>






<h1>Request Group rate</h1>
<form>
    <input type="hidden" name="referrer">
    Name: <input type="text" id="fieldName" name="name"><br>
    Group Size: <input type="text" name="groupSize"><br>
    Email: <input type="email" name="email"><br>
    <input type="submit" value="Submit">
</form>
<script>
    $(document).ready(function() {
        $('input[name="referrer"]').val(document.referrer);
    });
</script>

Cross-page test file.

var Browser = require('zombie'),
    assert = require('chai').assert;

var browser;

suite('Cross-Page Tests', function(){

    setup(function(){
        browser = new Browser();
    });

    test('requesting a group rate quote from the hood river tour page should ' +
            'populate the hidden referrer field correctly', function(done){
        var referrer = 'http://localhost:3000/tours/hood-river';
        browser.visit(referrer, function(){
            browser.clickLink('.requestGroupRate', function(){
                assert(browser.field('referrer').value === referrer);
                done();
            });
        });
    });

    test('requesting a group rate from the oregon coast tour page should ' +
            'populate the hidden referrer field correctly', function(done){
        var referrer = 'http://localhost:3000/tours/oregon-coast';
        browser.visit(referrer, function(){
            browser.clickLink('.requestGroupRate', function(){
                assert(browser.field('referrer').value === referrer);
                done();
            });
        });
    });

    test('visiting the "request group rate" page dirctly should result ' +
            'in an empty value for the referrer field', function(done){
        browser.visit('http://localhost:3000/tours/request-group-rate', function(){
            assert(browser.field('referrer').value === '');
            done();
        });
    });

});

package.json

{
  "name": "meadowlark",
  "version": "1.0.0",
  "description": "A demo app made in Node with Express",
  "main": "meadowlark.js",
  "scripts": {
    "test": "test"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/SisypheanPivot/meadowlark.git"
  },
  "keywords": [
    "demo",
    "travel"
  ],
  "author": "Nicholas Dowling",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/SisypheanPivot/meadowlark/issues"
  },
  "homepage": "https://github.com/SisypheanPivot/meadowlark#readme",
  "dependencies": {
    "express": "^4.13.4",
    "express3-handlebars": "^0.5.2"
  },
  "devDependencies": {
    "chai": "^3.5.0",
    "mocha": "^2.4.5",
    "zombie": "^4.2.1"
  }
}

mocha no work

hello , i learn ch05. but when i open two terminal . the first code 'node meadowlark.js'. the second code ' mocha -u tdd -R qa/tests-crosspage.js 2>/dev/null' . it's nothing to show me in the first terminal. can you help me . thank you very much ----- orz

Tags for Chapters 19 & 20?

Been a fanboy of your excellent manual since I found it under my Xmas tree last year--and a close student of this repo as I've jimmied the code over the past month, your routes/handlers refactor being a particularly illuminating revision.

In the interest of wringing every last iota of template value out of your book, and since nobody's yet bothered you about it, may I just take a moment to formally beg you share tags for the finished states of the Security and API chapters?

I've been trying to manually refactor the code in Chaps 18 & 19 to match the repo on my own, but it's been tricky. Some time with Chapter 20: Debugging will likely help get me through my troubles, but a reference solution to those set-ups would be a godsend: working with Passport and various APIs was a big motivation to get this far!

Much obliged for your consideration, anyways, and also for the book. Seriously classic stuff.

Handlebars not seeing "partials.weather.locations"

Hi -

I'm working on the weather widget example. The template renders, but it does not render the Each Block. A console.dir(partials) on the template returns "partials is not defined". I've reduced the weather locations array to a single location and name for testing.

weather.handlebars:

<div class="weatherWidget">

          {{#each partials.weather.locations}}
              <h3>{{name}}</h3>
              {{/each}}

      {{! Below code is rendering}}
          <small>Source: <a href="http://www.wunderground.com">Weather Underground</a></small>
</div>

Thanks!
Robert

set custom layout fail

i have already create an custom.handlebars in views/layouts/. it didn't work. eventhough i set layoutDirs when create the engine.

is there something wrong with my code?

app.get('/custom-layout', function (req ,res) {
  res.render('custom-layout', {layout: 'custom'});
});

here is error info:

Error: Failed to lookup view "custom-layout" in views directory "/home/zhlin/Co
de/Express/chap3/site/views"
...

Chapter 05 - First Mocha Test

I'm getting 2 failures. 1 for sure is the oregon page as it's not written but the other is dumbfounding me. I've checked spelling and can't figure it out.
**** (i've seen an earlier thread on zombie versions too so I've downgraded to version 3.1.1)

the error is

Cross-Page Tests
1) requesting a group rate quote from the hood river tour page should populate the referrer field
2) requesting a group rate from the oregon coast tour page should populate the referrer field
โœ“ visiting the "request group rate" page directly should result in an empty referrer field

1 passing (4s)
2 failing

  1. Cross-Page Tests requesting a group rate quote from the hood river tour page should populate the referrer field:
    Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

  2. Cross-Page Tests requesting a group rate from the oregon coast tour page should populate the referrer field:
    Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

**** note, just saw the missing {{section}} added to the request group rate page to allow jquery, I've added that and now all 3 of the test fail for the same reason, exceed timeout for done()

here's the error from terminal

Error: Missing helper: "section"
at Object. (/Users/Mike/Training/Meadowlark/node_modules/handlebars/dist/cjs/handlebars/base.js:86:13)
at Object.eval (eval at createFunctionContext (/Users/Mike/Training/Meadowlark/node_modules/handlebars/dist/cjs/handlebars/compiler/javascript-compiler.js:221:23), :6:91)
at ret (/Users/Mike/Training/Meadowlark/node_modules/handlebars/dist/cjs/handlebars/runtime.js:159:30)
at ret (/Users/Mike/Training/Meadowlark/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js:488:21)
at ExpressHandlebars._renderTemplate (/Users/Mike/Training/Meadowlark/node_modules/express-handlebars/lib/express-handlebars.js:247:12)
at ExpressHandlebars. (/Users/Mike/Training/Meadowlark/node_modules/express-handlebars/lib/express-handlebars.js:173:21)

req.user.name is undefined

I'm following the Chapter 18, 'Security'. I was able to get the login working with no problems, but I can't access the user information through req.user.

I googled the problem and everyone said that the problem is that express-session isn't correctly enabled, but I'm using sessions in the app (like the flash thing) and the setup is equal to the project files:

app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())

var MongoSessionStore = require('session-mongoose')(require('connect'))
var sessionStore = new MongoSessionStore({
    url: credentials.mongo[app.get('env')].connectionString
})

app.use(require('cookie-parser')(credentials.cookieSecret));
app.use(require('express-session')({
    store: sessionStore,
    resave: false,
    saveUninitialized: false,
    secret: credentials.cookieSecret,
}));

npm zombie install error

installing zombie produces this error.

cc@DELL:~/projects/meadowlark/site$ npm install --save-dev zombie
npm WARN package.json [email protected] No repository field.
npm WARN package.json [email protected] No README data

> [email protected] install /home/cc/projects/meadowlark/site/node_modules/zombie/node_modules/jsdom/node_modules/contextify
> node-gyp rebuild

gyp ERR! build error 
gyp ERR! stack Error: not found: make
gyp ERR! stack     at F (/usr/lib/node_modules/npm/node_modules/which/which.js:43:28)
gyp ERR! stack     at E (/usr/lib/node_modules/npm/node_modules/which/which.js:46:29)
gyp ERR! stack     at /usr/lib/node_modules/npm/node_modules/which/which.js:57:16
gyp ERR! stack     at Object.oncomplete (evalmachine.<anonymous>:108:15)
 System Linux 3.2.0-4-686-pae
gyp ERR! command "node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/cc/projects/meadowlark/site/node_modules/zombie/node_modules/jsdom/node_modules/contextify
gyp ERR! node -v v0.10.37
gyp ERR! node-gyp -v v1.0.1
gyp ERR! not ok 

> [email protected] install /home/cc/projects/meadowlark/site/node_modules/zombie/node_modules/ws/node_modules/utf-8-validate
> node-gyp rebuild

gyp ERR! build error 
gyp ERR! stack Error: not found: make
gyp ERR! stack     at F (/usr/lib/node_modules/npm/node_modules/which/which.js:43:28)
gyp ERR! stack     at E (/usr/lib/node_modules/npm/node_modules/which/which.js:46:29)
gyp ERR! stack     at /usr/lib/node_modules/npm/node_modules/which/which.js:57:16
gyp ERR! stack     at Object.oncomplete (evalmachine.<anonymous>:108:15)
gyp ERR! System Linux 3.2.0-4-686-pae
gyp ERR! command "node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/cc/projects/meadowlark/site/node_modules/zombie/node_modules/ws/node_modules/utf-8-validate
gyp ERR! node -v v0.10.37
gyp ERR! node-gyp -v v1.0.1
gyp ERR! not ok 
npm WARN optional dep failed, continuing [email protected]

> [email protected] install /home/cc/projects/meadowlark/site/node_modules/zombie/node_modules/ws/node_modules/bufferutil
> node-gyp rebuild

gyp ERR! build error 
gyp ERR! stack Error: not found: make
gyp ERR! stack     at F (/usr/lib/node_modules/npm/node_modules/which/which.js:43:28)
gyp ERR! stack     at E (/usr/lib/node_modules/npm/node_modules/which/which.js:46:29)
gyp ERR! stack     at /usr/lib/node_modules/npm/node_modules/which/which.js:57:16
gyp ERR! stack     at Object.oncomplete (evalmachine.<anonymous>:108:15)
gyp ERR! System Linux 3.2.0-4-686-pae
gyp ERR! command "node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/cc/projects/meadowlark/site/node_modules/zombie/node_modules/ws/node_modules/bufferutil
gyp ERR! node -v v0.10.37
gyp ERR! node-gyp -v v1.0.1
gyp ERR! not ok 
npm WARN optional dep failed, continuing [email protected]
npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] install script.
npm ERR! This is most likely a problem with the contextify package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls contextify
npm ERR! There is likely additional logging output above.

npm ERR! System Linux 3.2.0-4-686-pae
npm ERR! command "/usr/bin/node" "/usr/bin/npm" "install" "--save-dev" "zombie"
npm ERR! cwd /home/daniel/projects/meadowlark/site
npm ERR! node -v v0.10.37
npm ERR! npm -v 1.4.28
npm ERR! code ELIFECYCLE
npm ERR! not ok code 0

has anybody else experienced this?

Bundles?

In Chapter 16, you briefly mention your bundle module, and show how to use it, but you don't explain it. I don't understand how the 'stuff' in the config.js file relates to stuff like this:

{{#each _bundles.css}}

{{/each}}

I understand, I think, what I'm doing when I bundle, but you aren't explaining what happens. How would I know, or where would I find that _bundles.css relates to bundles.clientJavaScript.contents (which is what I'm pretty sure is what's happening here)?

Cannot read property 'Store' of undefined

I'm using the downloaded code to test the app as I work through the chapters and I'm running into a problem:

\node_book\meadowlark\site\node_modules\session-mongoose\index.js:261
})(connect.session.Store);
^
TypeError: Cannot read property 'Store' of undefined
at module.exports (\node_book\meadowlark\site\node_modules\session-mongoose\index.js:261:23)
at Object. (\node_book\meadowlark\site\meadowlark.js:88:52)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
12 Jul 08:46:33 - [nodemon] app crashed - waiting for file changes before starting...

Any ideas what's happening here? I made sure I had the latest versions of the node modules. Some posts suggest that I should add node-connect, but that didn't change anything. Any thoughts?

Error when testing ch04

I am new to Node and Express. I like to test the code as I read along your book.
I cannot seem to get the code to work when I test it. Here is what I have done.

  • First i clone your repo, then checkout tag ch04.
  • run npm install
  • run node meadowlark.js
    Then I received the following error.
    issue

I am not sure if i have done something wrong. Please help. Thanks

Ch10 Tag - Error with app.use( require(' express-session')());

I have been working in Chapter 9 for Cookies and Sessions. With my own web app that I have been building as I follow along with your book is not able to load my root page when I attempt your example. The console shows errors with express-sessions depreciated with options for resave, saveUninitialized, and req.secret (provide secret option). I tested your ch10 tag to see how to debug my mistake and found the same error.

ch10 copy

I then went and looked up the express-sessions on github for more info. I found the following code with one option added:

This works:
var session = require('express-session')
app.use(session({secret: 'keyboard', resave: true}));

This produces errors:
var session = require('express-session')
app.use(session({secret: credentials.cookieSecret, resave: true}));

It is unclear how I can refactor your example to work, so the secret key will be hidden via module.export in the credentials.js file. Please let me know your advice for correcting this issue. Thanks.

Ch11: Encapsulating Email Functionality

With the credentials.js file not working properly I have replaced the code with environmental vars. When I run the ./lib/email.js to test the functionality from this chapter example, the server is throwing an error stating there is no method 'send' at the line:

emailService.send(...);

I might be wrong, but are we able to access the send as a method when it is placed within the return statement of the email.js file?

chapter 5 - getting 404 error in dev mode

I'm a noob who does not know how to diagnose this problem. I'm on page 44 and I have just added the pageTestScript. Upon running the site the qa js files produce a 404 error message when I inspect the page source. everythin loads but the tests-.js files.

My code is typed identically to the book. I upgraded from express3-handlebars to express-handlebars and made sure package.json reflected these changes. It looks like this.

in package.json:

"dependencies": {
    "express": "^4.12.3",
    "express-handlebars": "^2.0.0"
  },

in meadowlark.js:

var handlebars = require('express-handlebars').create({defaultLayout: 'main'});
...
app.use(function(req, response, next){
    response.locals.showTests = app.get('env') !== 'production' && 
    req.query.test === '1';
    next();// pass control to the next handler
})
...
app.get('/about', function(req,response){
    response.render('about', { 
        fortune: fortune.getFortune(),
        pageTestScript: '/qa/tests-about.js' 
    });
});

in main.handlebars:

{{#if showTests}}
        <div id= "mocha"></div>
        <script src="/vendor/mocha.js"></script>
        <script src="/vendor/chai.js"></script>
        <script>
            mocha.ui('tdd');
            var assert = chai.assert;
        </script>
        <script src="/qa/tests-global.js"></script>
        {{#if pageTestScript}}
            <script src="{{pageTestScript}}"></script>
        {{/if}}
        <script>mocha.run();</script>
    {{/if}}

I get this error:
meadowlark errors

I know this is probably a simple problem to fix but please bare with me I am teaching myself web development. Thanks

CS

cannot find module './credentials.js'

I am new for express and node.

After I download the project from git and I try to compile and run it.

C:\git\web-development-with-node-and-express>npm install
...
C:\git\web-development-with-node-and-express>node meadowlark.js

module.js:340
    throw err;
    ^
Error: Cannot find module './credentials.js'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (C:\git\web-development-with-node-and-express\meadowla
rk.js:13:19)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)

I do not know what the './credentials.js' for and how to make it can find it?

Chapter 7 - Partials - Problem with express-handlebars

When you install express3-handlebars - as the book suggests - npm gives you a deprecated warning because it was moved to express-handlebars. So I used express-handlebars until now because I seem to be reasonable to use the latest tools and I did not think that this would break anything.

npm WARN deprecated [email protected]: THIS PACKAGE HAS BEEN RENAMED TO: express-handlebars

At least until the following error occurred after I added the weather partial:

Error
    at Object.<anonymous> ([...]Meadowlark/node_modules/express-handlebars/node_modules/handlebars/dist/cjs/handlebars/exception.js:29:23)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> ([...]Meadowlark/node_modules/express-handlebars/node_modules/handlebars/dist/cjs/handlebars/base.js:3:17)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)

After finding this StackOverflow post with the same Error code (but no solution) I found out, that it had something to do with the res.locals.partials

If I exchange express-handlebars with the deprecated express3-handlebars my code works fine. Also, when I update the chapter8 solution code to express-handlebars the same error occurs.

Does anyone know why it does not work anymore? Maybe a workaround/different solution?

typo in ch15/meadowlark.js

line 90:
var sessionStore = new MongoSessionStore({ url: credentials.mongo[app.get('env'].connectionString });

should be

var sessionStore = new MongoSessionStore({ url: credentials.mongo[app.get('env')].connectionString });

( ie ('env'] -> ('env)] )

Chapter 8 - problem with jquery-file-upload

When I run the example code of this chapter, after I filled the form and uploaded png files, clicking the sumbit button will prompt to submit a file. It seems that the jquery-file-upload plugin has sent the request when uploading files. The form submission and the file upload are not synchronized.

ch05 tests-crosspage.js fails to find 'referrer' field

I've tried multiple versions of zombie but I haven't been able to solve this issue. My tests fail with error saying it cannot read value of null.

assert(browser.field('referrer').value === referrer);

I have the latest versions of Xcode command line tools and node.js

Chapter 7 - Handlebars.compile is confused with partials.weather and weather.handlebars

I notice that the inclusion of the partial {{> weather}} in the home.handlebars file is getting confused between the name of the widget weather.handlebars and the partial variable located in res.locals.partials.weather because a saw this error on my browser:

Error: You must pass a string or Handlebars AST to Handlebars.compile. You passed [object Object] at Object.compile...

So, I decided to replace res.locals.partials.weather with res.locals.partials.weatherData. Finally, the weather.handlebars file will look like this:

<div class="weatherWidget">
  {{#each partials.weatherData.locations}}
    <div class="location">
      <h3>{{name}}</h3>
      <a href="{{forecastUrl}}">
        <img src="{{iconUrl}}" alt="{{weather}}">
        {{weather}}, {{temp}}
      </a>
    </div>
  {{/each}}
  <small>
    Source: <a href="http://www.wunderground.com">Weather Underground</a>
  </small>
</div>

These changes worked well for me. Hope it helps.

Callback function of connect-rest

I'm a bit confused about the use of connect-rest.

The third passed parameter is the 'callback' function. What exactly this function does? It returns what you want as json? Why the first argument is "null"? The documentation doesn't seem to explain much about this

Suggestion for ch 7 "Sections" topic

In ch7, there's a section that dives into the concept of "Sections" within your view. Cool way to use Handlebars helpers but I wanted to offer some feedback to make it a little clearer:

  1. You should explain what options.fn() does. I had to go to the Handlebars site to find a reference to it and even then it wasn't very clear on what it actually does.
  2. The section in the book ends without explaining where to add the _section.head & _section.jquery code. I assumed it was main.handlebars so I added it there.
  3. There were no instructions on how to reference the new 'jquery-test.handlebars' template so I just created a simple route to call it. The book should mention something about that.

ch13 - error on cart checkout when when using clustering

Hi,
thx for the book and this repository. After checking out ch13 I am facing the following issue:

  1. node meadowlark_cluster.js
  2. browse to hood-river and add a tour to the cart
  3. checkout
  4. error - 404
    (everything works fine when running meadowlark.js directly... the problem seems to be around the clustering(

It looks like the express framework throws an error when rendering the check out

app.get('/cart/checkout', function(req, res, next) {
    var cart = req.session.cart;
    if (!cart) next();
    res.render('cart-checkout');
});

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:689:11)
at ServerResponse.res.set.res.header (/Users/kimkopowski/nodeJs/web-development-with-node-and-express/node_modules/express/lib/response.js:551:10)

help or comment appreciated!

Getting an error - Cannot find module 'express-session'

I am following the book and I get this error when I try to start my server. I tried to install the module express-session but doesn't work. It says

throw err;
Cannot find module 'express-session'

on this line - app.use(require('express-session')({ store : sessionStore }));

How can i solve this problem?

Chapter 5: Mocha and Chai Global Tests

Up through chapter 5 I have been able to successfully run your examples. However, when I get into this chapter, I am finding many issues. First, to get the tests-global.js file to run I have to remove the if conditional statements. I am unable to apply ?test=1 to the query string and have it initiate the tests you have established so that we can hide the testing functionality.

Second I placed this code in the home.handlebars file to get the test to run with the if conditionals removed. When I run this test on the home page, I do see the global test run on the browser with 0 passes and 1 failure. However, I find an error with the assert statement also displayed in the browser:
AssertionError: Unspecified AssertionError

I reviewed the documentation for chai assert statement (http://chaijs.com/api/assert/#assert) and find we should be using a form as follows: assert(expression, message) but your code is not written to this format. If you could please provide some clarification?

Views Folder

I'm wondering how doing that:

app.get('/about', function(req, res) {
 res.render('about')
})

Can render the file views/about.html. I didn't specify anywhere where my views folder is. Taking a look on the source of express-handlebars.js I can see that the file set two pathnames, one for the 'layouts' and other for 'partials'. But I don't see anywhere a reference to views/. From where this is coming from?

Chapter 6 Example Code Typos

Hello @EthanRBrown

I am really enjoying the book so far. I was reading through the example code snippets for the Providing an API section of Chapter 6 when I came across a couple typos (or at least what I thought may be typos). I wasn't sure if this was an appropriate place to bring these to your attention as they aren't part of the Meadowlark app.

First one I noticed was on page 66 (hard copy) in the first paragraph of the Providing an API section. It says

Examples 6-11 and 6-12 use the following "products" array...

I wasn't sure if this was supposed to say "tours" as that is what the array is called or if you were just referring to it as products as tours are a product a tourism company provides.

Secondly, in Example 6-12 where you format for text/plain you are sending the toursXml string and not the toursText string.

Apologies in advance if these have already been fixed in the eBooks. I just purchased the hard copy a couple days ago so assumed it was a recent version.

Chapter 14 - TypeError: Cannot read property 'requiresWaiver' of null

From the end of Chapter 14, with the code from github I am seeing the following.

TypeError: Cannot read property 'requiresWaiver' of null
at /home/marc/meadowlark/site/lib/cartValidation.js:5:58
at Array.some (native)
at Object.module.exports.checkWaivers as handle
at next_layer (/home/marc/meadowlark/site/node_modules/express/lib/router/route.js:103:13)
at /home/marc/meadowlark/site/handlers/cart.js:30:4
at _fulfilled (/home/marc/meadowlark/site/node_modules/q/q.js:834:54)
at self.promiseDispatch.done (/home/marc/meadowlark/site/node_modules/q/q.js:863:30)
at Promise.promise.promiseDispatch (/home/marc/meadowlark/site/node_modules/q/q.js:796:13)
at /home/marc/meadowlark/site/node_modules/q/q.js:604:44
at runSingle (/home/marc/meadowlark/site/node_modules/q/q.js:137:13)
at flush (/home/marc/meadowlark/site/node_modules/q/q.js:125:13)
at nextTickCallbackWith0Args (node.js:419:9)
at process._tickDomainCallback (node.js:389:13)

I have deleted the node_module directory and reinstalled using npm install.

Invalid csrf token when on multipart/form-data

When I'm using formidable and upload image fields in forms with enctype=multipart/form-data, I'm getting "invalid csrf token" error message. When I remove enctype from the form, it works.

Any ideas?

Thanks

My middlewares:

    app.use(expressSession({                                                                                                                                                                                                  
         cookie: {                                                                                                                                                                                                                  
             maxAge: 60000                                                                                                                                                                                                          
         },                                                                                                                                                                                                                         
         secret: '...',                                                                                                                                                                                      
         resave: true,                                                                                                                                                                                                              
         saveUninitialized: true                                                                                                                                                                                                    
    }));

    app.use(bodyParser.json());                                                                                                                                                                                               
    app.use(bodyParser.urlencoded({extended: false}));                                                                                                                                                                        

    app.use(cookieParser('...'));                                                                                                                                                                      

    app.use(require('csurf')());                                                                                                                                                                                              
    app.use(function(req, res, next) {                                                                                                                                                                                        
          res.locals._csrfToken = req.csrfToken();                                                                                                                                                                                   
          next();                                                                                                                                                                                                                    
    });


    //                                                                                                                                                                                                                             
    // 404                                                                                                                                                                                                                         
    //                                                                                                                                                                                                                             
    app.use(function (err, req, res, next) {                                                                                                                                                                                  
         res.status(400);                                                                                                                                                                                                           
         res.send(err.message);                                                                                                                                                                                                     
    });

problem length jquery

assert($('a[href="/contact"]').length);

Hi! dear my friend

your book is great for me
but now have problem
I can't solve this problem
let me know how to fix it

2015-12-18 12 21 27

2015-12-18 12 22 01

ch3 : {{{body}}} for handlebar

I came from front-end to back-ebd {{{body}}}of handlebar is close to data-binding in AngularJS and it causes troubles. Any sugesstion/replacement except Jade?

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.