azat-co / expressworks

Learn Express.js from the author of one of the best books on Express.js—Pro Express.js— with this workshop that will teach you basics of Express.js.
MIT License
715 stars 220 forks source link

Use of middleware in form post #28

Closed jonnyarnold closed 9 years ago

jonnyarnold commented 10 years ago

[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)
ayong-mdsol commented 10 years ago

Yeah I am getting errors with connect.

My solution:

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

// Add middleware
app.use(connect.urlencoded());

app.post('/form', function (req, res) {
  var revStr = req.body.str.split('').join('');
  res.send(revStr);
});

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

The output:

Verifying "GOOD OLD FORM"...

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

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)
finnp commented 10 years ago

You are correct with your observation. I created a pull request to reflect the changes in express/connect.

danielbush commented 10 years ago

Ditto for me. Been wrestling with this for a while, using connect 3.1 . So I ended up doing: npm install body-parser # from expressjs https://github.com/expressjs then: var bp = require('body-parser') app.use(bp.urlencoded({extended: true}))

ayong-mdsol commented 10 years ago

Even when using body parser it still doesnt work

oakley808 commented 10 years ago

Yeah. I was unable to get this to work either. Check out the "expected" result when I verify it. It's expecting an error?!

$ expressworks verify 3-form.js 
Verifying "GOOD OLD FORM"...

ACTUAL                             EXPECTED
------                             --------
"Express.js rocks!"             != "Cannot POST /form"            
# FAIL

Here's the meat of my code:

var bodyparser = require('body-parser');

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

app.post( '/form', function(req, res){
    var result = req.body.str.split('').reverse().join('') ;
    res.send( result );
});
CamiloMM commented 10 years ago

@oakley808 Got it to work, first npm install body-parser, then

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

However, the fact that the task description even says

NOTE Avoid using soon to be depricated bodyParser() middleware.

Is disturbing.

oakley808 commented 10 years ago

@CamiloMM You can suppress that error notification using: app.use( bodyparser.urlencoded( {extended: true} ));

Did you run expressworks verify myprogram.js and get it to pass?

CamiloMM commented 10 years ago

@oakley808 I didn't get any error notification, I was saying about the task description itself. And yeah, that exact code I posted passes the verify. Just finished expressworks now, btw :)

oakley808 commented 10 years ago

@CamiloMM I just meant I thought you should be able to suppress the message

NOTE Avoid using soon to be depricated bodyParser() middleware.

by adding app.use( bodyparser.urlencoded( {extended: true} ));

I think there must be something broken in my expressworks. I copied the official solution for the STATIC exercise and it still failed to verify:

$ cat 4-static-cheating.js && expressworks verify 4-static-cheating.js 
var path = require('path')
var express = require('express')
var app = express()

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

app.listen(process.argv[2])Verifying "STATIC"...

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

Your solution to STATIC didn't match the expected output.
Try again!
CamiloMM commented 10 years ago

@oakley808 Again, that message is only shown after selecting the task, in the task description, at the bottom (before any of my code is ran), which strikes me as very jarring because due to it being outdated, the solution to the problem is to do exactly what it tells you not to. When I verify my code, I do not get any sort of warning message. Screenshot:

screenshot

Try to just copy and paste my code and tell me if it works.

mpmckenna8 commented 10 years ago

On my first tries on this problem I was also getting a

Cannot POST /form

message. After shutting down a application using port 3000 it worked as expected.

Recommend letting people know to have port 3000 open for running the tests and verification.

jdivock commented 9 years ago

@oakley808 Odds are you're getting the cannot post because the solution is trying to run on port 3001 and something is already running there

To see for yourself you can run

sudo lsof -i :3001

You'll probably see process running.

azat-co commented 9 years ago

58