Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot POST form node.js - express

Tags:

Using express 3.1.0 I have a super simple form:

<form action="/signup" method="post">     <div>         <label>Username:</label>         <input type="text" name="username"/><br/>     </div>     <div>         <label>Password:</label>         <input type="password" name="password"/>     </div>     <div><input type="submit" value="Sign Up"/></div> </form> 

and in the app.js:

/**  * Module dependencies.  */  var express = require('express')   , routes = require('./routes')   , fs = require('fs')   , User = require('./models/User.js')   , user = require('./routes/user')   , http = require('http')   , path = require('path');  var app = express();  app.configure(function(){   app.set('port', process.env.PORT || 3000);   app.set('views', __dirname + '/views');   app.set('view engine', 'jade');   app.use(express.favicon());   app.use(express.logger('dev'));   app.use(express.bodyParser());   app.use(express.methodOverride());   app.use(app.router);   app.use(express.static(path.join(__dirname, 'public'))); });  app.configure('development', function(){   app.use(express.errorHandler()); });  app.get('/', routes.index); app.get('/form', function(req, res) {     fs.readFile('./form.html', function(error, content) {         if (error) {             res.writeHead(500);             res.end();         }         else {             res.writeHead(200, { 'Content-Type': 'text/html' });             res.end(content, 'utf-8');         }     }); });  app.post('/signup', function(req, res) {      var username = req.body.username;     var password = req.body.password;     User.addUser(username, password, function(err, user) {         if (err) throw err;         res.redirect('/form');     }); });  app.get('/users', user.list);   http.createServer(app).listen(app.get('port'), function(){   console.log("Express server listening on port " + app.get('port')); }); 

when trying to post this form i'm getting:

Cannot POST /signup 

and in the console:

"NetworkError: 404 Not Found - http://localhost:3000/signup" 

what am i missing here?

like image 380
baba-dev Avatar asked Feb 15 '13 20:02

baba-dev


1 Answers

Your example works for me. I removed the references to User, user, and routes so that I can run it and the HTTP POST is received and displayed correctly in the console.

app.post('/signup', function(req, res) {     var username = req.body.username;     var password = req.body.password;     console.log("post received: %s %s", username, password); }); 

I suspect the error is in your User.addUser() code.

like image 95
Hector Correa Avatar answered Oct 22 '22 13:10

Hector Correa