Git Product home page Git Product logo

expressworks's Introduction

expressworks

Learn Express.js from the author of one of the best books on Express.js—Pro Express.js—workshop to teach you basics of Express.js.

Hello World Express.js app

This workshop is based on workshopper and inspired by stream-adventure by @substack and @maxogden.

ExpressWorks will provide you with tasks and hints. You write the solutions to these problems. Then, after you wrote a solution as an Express.js app, ExpressWorks will verify your solution to the problem.

Video screencasts which walk you through setup and problems (spoiler alert): YouTube ExpressWorks. 📺💻😁

This workshop is brought to you by Azat Mardan, the author of Practical Node.js (free on GitHub)

Cheatsheet

You might want to download the free Express.js cheatsheet in PDF.

Languages

  • English
  • Spanish
  • French
  • Simplified Chinese
  • Traditional Chinese
  • Korean
  • Japanese

Contributors

117  Azat Mardan
55  Azat Mardanov
19  Christophe Porteneuve
10  Tyler Moeller
10  azat-co
 9  RamiroPinol
 8  Elias Meire
 8  Justin Porter
 6  billy3321
 4  Kohei TAKATA
 4  Shim Won
 3  Charlotte Spencer
 3  Harry Moreno
 3  Kaelig Deloumeau-Prigent
 2  Austin Corso
 2  Julian Mazzitelli
 2  Kevin Jayanthan
 2  Robbie Holmes
 2  Thomas Burette
 2  Victor Hugo
 2  intrueder
 1  Alessandro Lensi
 1  Alfredo Miranda
 1  Apricity
 1  Ayman Mahfouz
 1  Chuanfeng
 1  Daniel Geier
 1  Dylan Smith
 1  Eddie Hsieh
 1  Finn
 1  Gabe Fernando
 1  Giuseppe
 1  Hanbyul Jin
 1  Jessie Shi
 1  Johan Binard
 1  Jonny Arnold
 1  Kevin Kuhl
 1  Louis Pilfold
 1  Luis Del Águila
 1  Naitian Zhou
 1  Rich Trott
 1  Richard Kho
 1  Ryan Kois
 1  Timothy Gu
 1  Trevor Whitney
 1  Wojciech Gawronski
 1  brownman
 1  raj
 1  swisherb
 1  tdtsh

Make a PR to see your name here. ;-)

PS: via $ git shortlog -n -s. Please add yourself to the list when making a pull request.

Installation (Recommended)

Recommended global installation:

$ npm install -g expressworks
$ expressworks

If you see errors, try:

$ sudo npm install -g expressworks
$ expressworks

Local Installation (Advanced)

Run & install locally:

$ mkdir node_modules
$ npm install expressworks
$ cd node_modules/expressworks
$ node expressworks

Optional step that gives you the global command (expressworks) in the Terminal/command prompt:

$ npm link
$ expressworks

Usage

$ expressworks

Note: ExpressWorks depends on a local copy of Express being available in your project folder. To do the exercises, make sure to install the Express.js with

$ npm init
$ npm install [email protected]

See Offline Setup for more required dependencies.

ExpressWorks understands these commands:

Usage

  expressworks
    Show a menu to interactively select a workshop.
  expressworks list
    Show a newline-separated list of all the workshops.
  expressworks select NAME
    Select a workshop.
  expressworks current
    Show the currently selected workshop.
  expressworks run program.js
    Run your program against the selected input.
  expressworks verify program.js
    Verify your program against the expected output.

Offline Setup

If you would like to setup all node packages beforehand, you can complete this workshop offline. Here are all the modules to install with exact versions that this workshop supports:

$ npm install [email protected]
$ npm install [email protected]
$ npm install [email protected]
$ npm install [email protected]

Note: You need to have node_modules or packagen.json in your project folder before installing dependencies. Run $ mkdir node_modules or $ npm init to create one of them.

Reset

If you want to reset the list of completed tasks, clean the ~/.config/expressworks/completed.json file.

Hello World Express.js app

More Information

Check out [Practical Node.js (free on GitHub) and free Express.js cheatsheet in PDF.

Steps

Hello World

Create an Express.js app that runs on localhost:3000, and outputs "Hello World!" when somebody goes to root '/home'.

process.argv[2] will be provided by expressworks to you, this is the port number.

Pug

Create an Express.js app with a home page (/home) rendered by pug template engine, that shows current date (toDateString).

Good Old Form

Write a route ('/form') that processes HTML form input (<form><input name="str"/></form>) and prints backwards the str value.

Static

Apply static middleware to server index.html file without any routes. The index.html file is provided and usable via process.argv[3] value of the path to it. However, you can use your own file with this content:

  <html>
    <head>
      <link rel="stylesheet" type="text/css" href="/main.css"/>
    </head>
    <body>
      <p>I am red!</p>
    </body>
  </html>

Stylish CSS

Style your HTML from previous example with some Stylus middleware. The path to main.styl file is provided in process.argv[3] or you can create your own file/folder from these:

  p
    color red

The index.html file:

  <html>
    <head>
      <title>expressworks</title>
      <link rel="stylesheet" type="text/css" href="/main.css"/>
    </head>
    <body>
      <p>I am red!</p>
    </body>
  </html>

Param Pam Pam

Create an Express.js server that processes PUT /message/:id requests, e.g., PUT /message/526aa677a8ceb64569c9d4fb.

As the response of this request return id SHA1 hashed with a date:

  require('crypto')
    .createHash('sha1')
    .update(new Date().toDateString().toString() + id)
    .digest('hex')

What's in Query

Write a route that extracts data from query string in the GET /search URL route, e.g., ?results=recent&include_tabs=true, and then transforms outputs it back to the user in JSON format.

JSON Me

Write a server that reads a file (file name is passed in process.argv[3]), parses it to JSON and outputs the content to the user with res.json(object).

expressworks's People

Contributors

amahfouz avatar austinmcorso avatar azat-co avatar billy3321 avatar bradhanson avatar chuanfengzhang avatar danielgeier avatar delaguilaluis avatar dylants avatar edhs0011 avatar finnp avatar gef756 avatar giuseppe-santoro avatar intrueder avatar justinrporter avatar kaelig avatar kohei-takata avatar limekin avatar marocchino avatar mirandaio avatar morenoh149 avatar nomadster avatar robbiethegeek avatar stamp711 avatar tburette avatar tdd avatar thejmazz avatar true1star avatar tylermoeller avatar victorhugoroch 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

expressworks's Issues

Expressworks run program.js doesn't work on Windows

Trying out the Hello World exercise in Windows, and I get an error:

C:\Users\Eric>node -v
v0.10.25

C:\Users\Eric>expressworks run expressworks.js
C:\Users\Eric\expressworks.js(1, 1) Microsoft JScript runtime error: Object expected

Not sure why it's running JScript. Node runs fine, and expressworks shows the menu fine.
My code looks like this:

var express = require("express");
var app = express();
app.get("/", function(req, res) {
    res.end("Hello World");
});
app.listen(process.argv[2]);

Good Old Form

My Code :

var express = require('express')
var bodyparser = require('body-parser')
var app = express()
app.use(bodyparser.urlencoded({extended:false}))
app.post('/form',function(req,res){

    req.body.str.split('').reverse().join('')

})

app.listen(process.argv[2]);

Its not running in the terminal
Its hanging up

jade expected output

the expected output is not right it seems. it is expecting "Hello World!"--which the solution for question 1.

What's In Query error when using res.send(obj)

using res.send(obj) gives an error

                 ACTUAL                                 EXPECTED                
────────────────────────────────────────────────────────────────────────────────

   "{"                                 !=    "{\"results\":\"recent\",\"type\":\"quote\",\"page\":\"8\"}"
   "  \"results\": \"recent\","        !=                                       
   "  \"type\": \"quote\","            !=                                       
   "  \"page\": \"8\""                 !=                                       
   "}"                                 !=                                       

────────────────────────────────────────────────────────────────────────────────

using res.end(JSON.stringify(obj)) works

problem 7 & 8 expected solutions are wrong

straight up wrong

expressworks verify program.js
Verifying "WHAT'S IN QUERY"...

ACTUAL:   "{\"results\":\"recent\",\"type\":\"quote\",\"page\":\"7\"}"
EXPECTED: "Cannot GET /search/?results=recent&amp;type=quote&amp;page=7"

# FAIL

Your solution to WHAT'S IN QUERY didn't match the expected output.
Try again!

basically you can pass this problem by omitting the route. If you use the provided solution (or a correct solution as in my case) you do not pass this problem. I would fix it myself but I'm unfamiliar with the way the expected solution is generated in https://github.com/azat-co/expressworks/blob/master/problems/whats_in_query/setup.js
Also found problem 8 does something similar. I tried npm install express in these directories just in case that was the issue but it is not. Let me know if you have trouble reproducing the bug.

Cannot find module 'workshopper-exercise'

Hi there!
When I run expressworks in the terminal and execute a problem I get this error:

module.js:338
throw err;
^
Error: Cannot find module 'workshopper-exercise'
at Function.Module._resolveFilename (module.js:336:15)
at Function.Module._load (module.js:278:25)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object. (/usr/local/lib/node_modules/expressworks/exercises/hello_world/exercise.js:3:21)
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)

I'm using OSX 10.6.8

banquisalm:express banquisalm$ node --version && express --version && expressworks --version
v0.12.0
4.11.2
[email protected]

Cheers ;)

Exercise 8 broken

$ expressworks verify 8-jsonme.js
Verifying "JSON ME"...

ACTUAL:   "[{\"title\":\"Express.js Guide\",\"tags\":[\"node.js\",\"express.js\"],\"url\":\"http://expressjsguide.com\"},{\"title\":\"Rapid Prototyping with JS\",\"tags\":[\"backbone.js\",\"node.js\",\"mongodb\"],\"url\":\"http://rpjs.co\"},{\"title\":\"JavaScript: The Good Parts\",\"tags\":[\"javascript\"]}]"
EXPECTED: "Cannot GET /books"

# FAIL

Your solution to JSON ME didn't match the expected output.
Try again!

"Cannot find module 'express'"

Trying to run the Hello World exercise on Linux:

eric@nas:~/expressworks$ expressworks run program.js
Running "HELLO WORLD!"...


module.js:340
    throw err;
          ^
Error: Cannot find module 'express'
    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> (/home/eric/expressworks/program.js:1:77)
    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)

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: connect ECONNREFUSED
    at errnoException (net.js:904:11)
    at Object.afterConnect [as oncomplete] (net.js:895:19)

My program.js looks like:

var express = require("express");
var app = express();
app.get("/", function(req, res) {
    res.end("Hello World");
});
app.listen(process.argv[2]);

ExpressWorks Hello, World

Wow. This is pathetic. I can’t get past the first exercise. Can anybody tell me what I’m doing wrong?

Some info. I am working on a Mac. Below are the commands that I type in the terminal and info on the output. After that is my code.

$ sudo npm install express --save
[entered password, much output, nothing in red...I think it went okay]
$ killall node
No matching processes belonging to you were found
$ expressworks run Express.js
35557
Cannot GET /home

Here’s my code
Express.js:

var express = require('express');
var app = express();
console.log(process.argv[2]);
app.get('/', function(req, res) {
        res.end('Hello World!');
})
app.listen(process.argv[2]);

"Cannot POST /form" in Good Old Form lesson.

I'm getting this error when trying to run or verify my solution. I've also tried the solution in the solution.js but it didn't work as well. I'm on Windows 7.

One thing it's worth mentioning is that I installed the "connect" module, since in the problem description, is said that "Express has urlencoded() middleware (from Connect library)". I'm not sure if I have to install it or if it is already a dependency of the Express module.

Exercise 1 fails to verify

  1. Running node v0.10.30 on Windows 7
  2. Installed express.
  3. Installed expressworks.
  4. Wrote the simple program
var express = require('express')
var app = express()

app.get('/', function(req, res) {
  res.write('Hello World!')
  res.end()
})
app.listen(process.argv[2])

And when I run:
expressworks verify myprog.js

it fails with the following message

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: connect ECONNREFUSED
    at errnoException (net.js:904:11)
    at Object.afterConnect [as oncomplete] (net.js:895:19)

*. Ran the same program with a hardcoded 3000 port and invoking localhost:3000 worked from the browser and showed the "Hello World!".

"Good Old Form: Official solution gives: Error: Cannot find module 'body-parser'

The official solution:

    var express = require('express')
    var bodyParser = require('body-parser')
    var app = express()    
    app.use(bodyParser.urlencoded({extended: false}))
    app.post('/form', function(req, res) {
      res.send(req.body.str.split('').reverse().join(''))
    })   
    app.listen(process.argv[2])

gives: Error: Cannot find module 'body-parser'

But this works:

var express = require('express');
var app = express();
app.use(express.urlencoded({extended: false}));
app.post('/form', function(req, res) {
    res.end(req.body.str.split('').reverse().join(''));
});
app.listen(process.argv[2]);

Verification failed with an error for all the exercises

This is the error output:

$ expressworks verify program.js                                                                                                    

?exercises.HELLO WORLD!.compare.title || common.exercise.compare.title || compare.title?

/home/ubuntu/.nvm/v0.11.14/lib/node_modules/expressworks/node_modules/workshopper-exercise/comparestdout.js:19
  return new Array(sz + 1).join(ch)
         ^
RangeError: Invalid array length
    at repeat (/home/ubuntu/.nvm/v0.11.14/lib/node_modules/expressworks/node_modules/workshopper-exercise/comparestdout.js:19:10)
    at center (/home/ubuntu/.nvm/v0.11.14/lib/node_modules/expressworks/node_modules/workshopper-exercise/comparestdout.js:25:13)
    at Exercise.transform (/home/ubuntu/.nvm/v0.11.14/lib/node_modules/expressworks/node_modules/workshopper-exercise/comparestdout.js:57:40)
    at Transform._read (/home/ubuntu/.nvm/v0.11.14/lib/node_modules/expressworks/node_modules/workshopper-exercise/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:184:10)
    at Transform._write (/home/ubuntu/.nvm/v0.11.14/lib/node_modules/expressworks/node_modules/workshopper-exercise/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:172:12)
    at doWrite (/home/ubuntu/.nvm/v0.11.14/lib/node_modules/expressworks/node_modules/workshopper-exercise/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:237:10)
    at writeOrBuffer (/home/ubuntu/.nvm/v0.11.14/lib/node_modules/expressworks/node_modules/workshopper-exercise/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:227:5)
    at Transform.Writable.write (/home/ubuntu/.nvm/v0.11.14/lib/node_modules/expressworks/node_modules/workshopper-exercise/node_modules/through2/node_modules/readable-stream/lib/_stream_writable.js:194:11)
    at Stream.ondata (stream.js:51:26)
    at Stream.emit (events.js:107:17)

Thanks!

JSON ME Unable to produce answer

My answer below is almost identical to the official answer and produces the same output, which is not "correct" in that it spans multiple lines and the correct output is all one line. I don't see anything wrong with my code.

var fs = require('fs');
var express = require('express');
var app = express();

app.get('/books', function(request, response) {
fs.readFile(process.argv[3], function(error, data) {
if (error) {
console.log(error);
}
response.json(JSON.parse(data));
});
});
app.listen(process.argv[2]);

Error running stylish css solution

Continuously getting this error:

Error: EACCES, open '/usr/local/lib/node_modules/expressworks/problems/stylish_css/public/main.css'

my solution:

var express = require('express')
var app = express()
var stylus = require('stylus')

var STATIC_DIR = process.argv[3]

app.use(stylus.middleware(STATIC_DIR))
app.use(express.static(STATIC_DIR))

app.listen(process.argv[2])

You can see in the screenshot that both solutions are not being loaded :(

stylish css doesn't accept solution

Big time noob here. Here is the code:

var express = require('express')
var path = require('path')
var app = express()
app.use(require('stylus').middleware( process.argv[3] + "/*.styl" ))
app.get('/main.css', function(req, res) {
res.end()
})
app.listen(process.argv[2])

main.css is being generated, but the GET doesn't fetch it. Please help!

Hello World task specification unclear

problem.txt specifies that the app should be run on 'localhost:3000', but later specifies that the port number will be provided by expressworks.

I have been recently working on the learnyounode & stream-adventure workshops so I assumed that the default of preferring process.argv[2] was still applying to this track.

Either the problem specification should clarify that port 3000 will be used, or the test should be updated to use a random port number which is supplied to the script.

Hello World Fails

The sample code for Hello World! is incorrect. The app.get statement directs uses to write:
app.get('/', function(){...})

when the correct answer is
app.get('/home', function(){...});

JSON ME output error?

When I try to test the last exercise i get this output:

ACTUAL:   "Cannot GET /books/"
EXPECTED: "Cannot GET /books"

Am I missing something or is just the solution wrong?

This issue can be tested against this simple example:

var app = require('express')();
app.listen(process.argv[2]);

save it in file.js the check it with:

expressworks verify file.js

excise 5 STYLISH CSS verify wrong

i have post the official solution but verify got wrong

$ expressworks verify  expressword.js 
Verifying "STYLISH CSS"...

ACTUAL                             EXPECTED
------                             --------
"Error: EACCES, open &#39;/usr/local/lib/node_modules/expressworks/problems/stylish_css/public/main.css&#39;"    "Error: EACCES, open &#39;/usr/local/lib/node_modules/expressworks/problems/stylish_css/public/main.css&#39;"
""                              != null                           
# FAIL

Your solution to STYLISH CSS didn't match the expected output.
Try again!

the official solution

var app = express()

app.use(require('stylus').middleware(process.argv[3]));
app.use(express.static(process.argv[3]));


app.listen(process.argv[2])

Expressworks keeps lingering processes running on Mac OS X

I have had two people running on two separate machines with weird Expects results.

From what I can tell it is due to some of the processes not being killed after the exercises have been completed. Because most of the exercises all run on the same port number, we are actually verifying to an old service.

running

$ ps aux | grep node

on these machines showed around 5 / 6 processes all belonging to the express works workshop.

Expressworks #8

I can't understand why this is not accepting my code, the output is the same. here is my program.js:

var express = require('express')
var app = express()
var fs = require('fs')

app.get('/books', function(req, res){
  var filename = process.argv[3]
  fs.readFile(filename, function(e, data) {
    if (e) return res.send(500)
    try {
      books = JSON.parse(data)
    } catch (e) {
      res.send(500)
    }
    res.json(books)
  })
})

app.listen(process.argv[2])

And this is what the response is to "expressworks verify program.js"

Your submission results compared to the expected:

             ACTUAL                                 EXPECTED                    
──────────────────────────────────────────────     ──────────────────────────────────

   "["                                 !=    "[{\"title\":\"Express.js Guide\",\"tags\":    [\"node.js\",\"express.js\"],\"url\":\"http://expressjsguide.com\"},{\"title\":\"Rapid Prototyping with  JS\",\"tags\":[\"backbone.js\",\"node.js\",\"mongodb\"],\"url\":\"http://rpjs.co\"},{\"title\":\"JavaScript: The  Good Parts\",\"tags\":[\"javascript\"]}]"
   "    \"title\": \"Express.js Guide\"," !=                                       
   "    \"tags\": ["                   !=                                       
   "      \"node.js\","                !=                                       
   "      \"express.js\""              !=                                       
   "    ],"                            !=                                       
   "    \"url\": \"http://expressjsguide.com\"" !=                                       
   "  },"                              !=                                       
   "  {"                               !=                                       
   "    \"title\": \"Rapid Prototyping with JS\"," !=                                        
   "    \"tags\": ["                   !=                                       
   "      \"backbone.js\","            !=                                       
   "      \"node.js\","                !=                                       
   "      \"mongodb\""                 !=                                       
   "    ],"                            !=                                       
   "    \"url\": \"http://rpjs.co\""   !=                                       
   "  },"                              !=                                       
   "  {"                               !=                                       
   "    \"title\": \"JavaScript: The Good Parts\"," !=                                       
   "    \"tags\": ["                   !=                                       
   "      \"javascript\""              !=                                       
   "    ]"                             !=                                       
   "  }"                               !=                                       
   "]"                                 !=                                       

────────────────────────────────────────────────────────────────────────────────

 ✗ Submission results did not match expected!

# FAIL

Your solution to JSON ME didn't pass. Try again!

Please help!

Verifying a solution goofs up terminal colours in Windows (in cmd, PowerShell, and others)

screenshot 2014-12-09 23 38 37

How?

ExpressWorks currently uses Workshopper v0.33 which colours code snippets with pygmentize. It passes the parameter terminal256 to pygmentize - but Windows terminals don't support 256 colours (as you saw they interpret these colours very differently!).

v0.4+ of Workshopper doesn't have this problem (it uses msee instead of pygmentize).

What's the fix?

Upgrade to v0.7.2, which is the newest version before v1. This didn't break anything when I tested it (briefly).

Incompatible with Express 4

The workshop is incompatible with the version 4 of Express.

The main problem is with the changes in middleware whose names have changed and are now unbundled from Express, this needing to be npm installed. This affects primarily good_old_form.

I've also add some errors during verify but couldn't attribute it with certainty to Express v4.

Jade problem checks against solution for hello world...

$ expressworks verify jade.js 
Verifying "JADE"...

ACTUAL                             EXPECTED
------                             --------
"<h1>Hello World</h1><p>Today is Wed Dec 11 2013.</p>" != "Hello World!"                 
# FAIL

Your solution to JADE didn't match the expected output.
Try again!

thanks for putting these lessons together!

STATIC - confused about instructions - where to learn more

I am finding the ExpressWorks instructions incomprehensible. Perhaps I am missing some prerequisites. I’ve written out my questions below to show the level of ignorance I am coming to this learning session with. If you have suggestions about where to go to learn what I need before I start, please let me know.

For example, Exercise 2 of 8 (static) says:

Please don't use ANY routes like app.get. ONLY static.

I wonder:

  1. What is a route?
  2. How can I learn about app?
  3. Static? Static as opposed to dynamic. What does that mean?

Your solution must listen on the port number supplied by process.argv[2].

I wonder:
4. What listens?
5. Is this like the Hello World one where I used this:
var app = express();
...
app.listen(process.argv[2]);

This is how you can call static middleware:

I wonder:
6. What is static middleware?
7. Where can I learn about it?

For this exercise expressworks will pass you the path:

app.use(express.static(process.argv[3] || path.join(__dirname, 'public')))

I wonder:
8. Is app var app = express();?
9. If so, what is express?
10. Where did the path variable come from?

This what I think is supposed to happen: process.argv[3] points to an HTML file. I am supposed get this HTML file and send it back in a response. I’m supposed to wait for a request from process.argv[2], but I don’t know if I’m supposed to parse that request in any way.

Exercise 6 verify wrong

I ran the verification of my solution twice, once thru sudo and once without. Both times, my solution seemed to work, but the verification step failed.

❯ expressworks verify index.js
Verifying "PARAM PAM PAM"...

ACTUAL                             EXPECTED
------                             --------
"663918365c1cf4aa90e1b997464837eeb216ff69" != "Cannot PUT /message/3f0a916de79d2a84e747342296f9ddb8"
# FAIL

Your solution to PARAM PAM PAM didn't match the expected output.
Try again!
❯ sudo expressworks verify index.js
Password:
Verifying "PARAM PAM PAM"...

ACTUAL                             EXPECTED
------                             --------
"467e7714bb0b77755e016a3737d2b8d961a3bd45" != "Cannot PUT /message/fd42373de17b40c04517a6e4c956778d"
# FAIL

Your solution to PARAM PAM PAM didn't match the expected output.
Try again!

My code (slightly different than the provided solution, but the same in spirit):

"use strict";

var express = require("express");
var crypto = require("crypto");

var app = express();
var port = process.argv[2];

app.put("/message/:id", function(req, res) {
    var id = req.params.id;
    var date = crypto.createHash("sha1").update(new Date().toDateString() + id).digest("hex");
    res.end(date);
});

app.listen(port);

I tried removing "use strict" as well as changing res.end(date) to res.send(date) to see if either was causing the verification script to fail to execute, but neither step resolved anything.

Official WHAT'S IN QUERY solution doesn't work

The official solution is:

    var express = require('express')
    var app = express()

    app.get('/search', function(req, res){
      var query = req.query
      res.send(query)
    })

    app.listen(process.argv[2])

but it doesn't work.

My solution was:

var express = require('express');
var app = express();

app.get('/search', function (req, res) {
  var query = req.query;
  delete query.__proto__;
  res.send(JSON.stringify(query));
});

app.listen(process.argv[2]);

I don't know if it's a good solution, but it worked.

expressworks run hello-world.js

Hi,

I copied the answer from the solution then also its not working..
can you guys tell me why iuts not working

C:\Users\Desktop\node-school\express> expressworks run hello-world.js
Running "HELLO WORLD!"...

module.js:340
throw err;
^
Error: Cannot find module 'express'
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. (C:\Users\Desktop\node-school\express\hello-world.js:1:77)
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)

events.js:72
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED
at errnoException (net.js:904:11)
at Object.afterConnect as oncomplete

Use of middleware in form post

[Express.js newbie!]

After having a hard time with error messages from Connect in the Form Posting exercise, I Googled the issue I was facing and came across this Stack Overflow question:
http://stackoverflow.com/questions/22209388/node-express-module-throwing-no-method-errors

The responder suggests the use of body-parser, as does the list of supported middleware on the Express.js website.

Am I mixing things up, or is the exercise outdated?

My solution, for reference:

var port = process.argv[2]

var express = require('express'),
    bodyParser = require('body-parser')

var app = express()
app.use(bodyParser.urlencoded())

app.post('/form', function(req, res) {
  res.end(
    req.body.str.split('').reverse().join('')
  )
})

app.listen(port)

node process should be killd after verified

OS X 10.9
node v0.10.21

I am trying to pass challenge 1, by need run verify twice, and after verified, the node web server both 3000 and 3001 should be killd, or it can't run challenge 2.

first time

$ expressworks verify 01-hello_world.js
Verifying "HELLO WORLD!"...

ACTUAL                             EXPECTED
------                             --------

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: connect ECONNREFUSED
    at errnoException (net.js:901:11)
    at Object.afterConnect [as oncomplete] (net.js:892:19)

second time

Verifying "HELLO WORLD!"...

ACTUAL                             EXPECTED
------                             --------
"Hello World!"                     "Hello World!"                 
# PASS

Your solution to HELLO WORLD! passed!

list node process

$ ps -awx | grep node
31914 ttys004    0:00.64 /usr/local/Cellar/node/0.10.21/bin/node 01-hello_world.js 3000
31915 ttys004    0:00.62 /usr/local/Cellar/node/0.10.21/bin/node /usr/local/share/npm/lib/node_modules/expressworks/problems/hello_world/solution.js 3001

static expected output is 'cannot get'

Shouldn't the expected output be the file?

Verifying "STATIC"...
ACTUAL                             EXPECTED
------                             --------
"<html>"                        != "Cannot GET /"                 
"  <head>"                      != null                           
"    <title>expressworks</title>" != null                           
"  </head>"                     != null                           
"  <body>"                      != null                           
"    <p>I am red!</p>"          != null                           
"  </body>"                     != null                           
"</html>"                       != null                           
# FAIL

GOOD OLD FORM problem: socket hang up

Here my code:
var express = require('express'),bodyparser = require('body-parser');
var app = express();
app.use(bodyparser.urlencoded({extended: false}));
app.post('/form',function(req,res){
req.body.str.split('').reverse().join('');
});
app.listen(process.argv[2]);

When I tried verify this code, I've got this:
events.js:85
throw er; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (_http_client.js:215:15)
at Socket.socketOnEnd (_http_client.js:300:23)
at Socket.emit (events.js:129:20)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)

Working (incorrect) solution to exercise 3

The proposed solution in good_old_form does not pass in my terminal. However, below is a working solution for all that it is worth:

var express = require("express");
var app = express();
var bodyparser = require("body-parser");

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

app.get("/form", function(req, res) {
    res.send(req.body.str.split('').revers().join(''));
});
app.listen(process.argv[2]);

Specify Node version.

First of all, this is a great app! Thank you for putting this together.

This ran fine using Node v0.11.8, but I was initially using an older version of node (v0.8.20) and kept getting errors.

It might be good to specify the node version on packages.json.

param_pam_pam could've used app.param

It'd be quite cool to show users how they can profit from app.param.

app.param('message_id', function(req, res, next, messageId) {
    req.computedHash = require('crypto')
        .createHash('sha1')
        .update(new Date().toDateString() + messageId)
        .digest('hex')
    next();
});

app.get('/:message_id', function(req, res, next) {
    res.send(req.computedHash);
});

Maybe worth mentioning there are two ways to approach this problem? Showing the beginners not everything needs to be handled in a route handler might be a nice tip!

WDYT?

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.