Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

alex gwartney
alex gwartney
8,849 Points

Node js post request in route is not working

so im trying to get a program that im working on to use a simple post route request. Now in the program im using express js not the natvie node js api. So hopefully some one who has ither used it or can figure it out would be able to help me out. But my problem is when i use app.post the server responds with a 404 can not get the request but if i use app.get or app.all it works just fine.

alex gwartney
alex gwartney
8,849 Points
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));


var server = app.listen(3000, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('Example app listening at http://%s:%s', host, port);
});

var getuser_Information;

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/data/db/');
var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
    // yay!
});
//testing the mogno db for createing a new table schema for a user login using the mognose api example
var UserSchema = mongoose.Schema({
    name:String
});


var usersinfo = mongoose.model('Kitten', UserSchema);
//sets up the log in


app.all('/',function(req, res) {
    getuser_Information = new usersinfo({ name:req.body.usernames});
    getuser_Information.save(function (err,silence) {
        if (err) return console.error(err);
        console.log(silence);
    });
    res.render('def',{
        firstnames:silence
    });
});

1 Answer

app.all() is meant to be used to run middleware.

If you want to handle different types of requests (GET and POST for instance), then chain them to app.route().

Example from the Express Routing Guide:

app.route('/book')
  .get(function(req, res) {
    res.send('Get a random book');
  })
  .post(function(req, res) {
    res.send('Add a book');
  })
  .put(function(req, res) {
    res.send('Update the book');
  });