1

I'm attempting to post data to my Node app

$.ajax({
    dataType: "json",
    method: "POST",
    url: "/users/new",
    data: {
        first_name: "Conor",
        last_name: "McGregor",
        id: 3
    },
    success: function (data) {
            console.log("Success: ", data);
    },
    error: function (error) {
        console.log("Error: ", error);
    }
});

. . . but am unsure of how to access the post data from within the app itself.

userRouter.route("/new")
    .post(function (req, res) {
        console.log(req);
        //console.log(req.body); 
    }

I have not been able to find the documentation for this after over an hour of searching. Any idea how to accomplish this?

Edit: Here's the entry point to my entire application. It's messy--sorry. :-(

"use strict";
var express = require("express");
var app = express();
var port = process.env.PORT || 5000;
var http = require("http");
var bodyParser = require("body-parser");
var pg = require("pg");
var connectionConfig = {
    user: "test_role",
    password: "password", // See what happens if you remove this value.
    server: "localhost", // I think this would be your database's server and not localhost, normally.
    database: "experiment", // The database's name
};
var connectionString = "postgres://test_role:password@localhost/experiment";

var server = http.createServer(function(req, res) {
    pg.connect(connectionString, function(error, client, done) {
        var handleError = function(error) {
            if (!error) {
                return false;
            }
            console.log(error);
            if (client) {
                done(client);
            }

            res.writeHead(500, {
                "content-type": "text/plain"
            });
            res.end("An error occurred.");
            return true;
        };

        if (handleError(error)) return;

        client.query("INSERT INTO visit (date) VALUES ($1)", [new Date()], function(error, result) {
            if (handleError(error)) {
                return;
            }
            client.query("SELECT COUNT(date) AS count FROM visit", function(error, result) {
                if (handleError(error)) {
                    return;
                }
                done();
                res.writeHead(200, {
                    "content-type": "text-plain"
                });
                res.end("You are visitor number " + result.rows[0].count);
            });
        });
    });
});

server.listen(3001);

var navigation = [{
    link: "/",
    text: "Home",
    new_window: false
}, {
    link: "/users",
    text: "Users",
    new_window: false
}, {
    link: "/contact",
    text: "Contact",
    new_window: false
}, {
    link: "/terms",
    text: "Terms",
    new_window: false
}];

var userRouter = require("./src/routes/userRoutes")(navigation);

// Routes
app.use("/users", userRouter);


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
// Serve static files from the public directory
app.use(express.static("public"));
app.use("/public", express.static("public"));

app.set("views", "./src/views");

// Specify EJS as the templating engine
app.set("view engine", "ejs");

app.get("/", function(req, res) {
    res.render("index", {
        title: "Art is long. Life is short.",
        list: ["a", "b", "c", "d"],
        navigation: navigation
    });
});
app.get("/terms", function(req, res) {
    res.render("terms");
});
app.get("/about", function(req, res) {
    res.render("about");
});
app.get("/contact", function(req, res) {
    res.render("contact");
});

var server = app.listen(port, function() {
    var port = server.address().port;
    console.log("Listening on port : " + port + " . . .");
});
Seth
  • 10,198
  • 10
  • 45
  • 68
Michael P.
  • 1,373
  • 3
  • 12
  • 33
  • really? https://www.google.com/search?q=post%20to%20node.js%20server specifically: http://stackoverflow.com/questions/12006417/nodejs-server-that-accepts-post-requests – Marc Guiselin Jan 22 '16 at 17:59
  • Yep. Attempting to access req.body was the first thing I tried before even foraging for answers online. Unfortunately, req.body comes back as undefined. – Michael P. Jan 22 '16 at 18:00
  • 1
    And you do of course have a [bodyParser](https://github.com/expressjs/body-parser) – adeneo Jan 22 '16 at 18:01
  • https://www.google.com/search?q=req.body%20empty produces a few results :) – Marc Guiselin Jan 22 '16 at 18:02
  • I've tried some of those. I've even tried the body-parser module that everyone's suggesting. I'm still getting "undefined." – Michael P. Jan 22 '16 at 18:13
  • Perhaps post more than just your user router. Amending your question with the the code which you initialize express and its middleware will help us to help you. – Seth Jan 22 '16 at 18:15
  • Done. I really, really appreciate your help. Thank you. – Michael P. Jan 22 '16 at 18:22
  • Have you checked chrome console for any errors after that ajax request is made? I just made a local isolated version of your app and it works perfectly fine. I see the body logged out. – Seth Jan 22 '16 at 18:48
  • Also, on a side note, you're overwriting the `var server` with the express app. – Seth Jan 22 '16 at 18:49
  • Chrome's not throwing any errors. I wonder if the issue could involve what you mentioned regarding the var server being overwritten by the Express app. – Michael P. Jan 22 '16 at 18:54

2 Answers2

1

You need to require a body parser, and call app.use on it before your route:

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

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

// Routes
app.use("/users", userRouter);

Express passes the request to each handler in the order they're declared, so body parser has to be used before your userRouter or else the body will not be parsed before your router gets called.

David Ulrich
  • 119
  • 4
  • This doesn't seem to work. I'm still getting "undefined." I've updated my post above with the code that initializes express and my middleware. – Michael P. Jan 22 '16 at 18:49
  • It looks like `app.use("/users", userRouter);` is out of order with `bodyparser`. The order you call `app.use` impacts the order express calls middleware, so bodyparser needs to be before your users route. – David Ulrich Jan 22 '16 at 18:59
1

The reason you're not finding any results is because you keep referring to node itself. Why not look for express-specific documentation, since you're not just using node only.

You need to, not only access req.body, but you must use the express body parser middleware.

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

// parse application/json
app.use(bodyparser.json());

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
  extended: true
}));

A simple express search for "express req.body undefined" or "express access POST data" would have pointed you in the right direction in minutes, rather than treading for hours. The key to researching a solution for something is to know what you're looking for. Also in your case, try and understand the difference between node: the platform, and express: the framework.

Seth
  • 10,198
  • 10
  • 45
  • 68
  • I understand the difference between Node and Express, but I figured that more results would be returned for Node rather than for Express, since the former is like the more popular of the two terms. (Plus, I was counting on the possibility that others who'd encountered the same issue were searching under Node rather than Express, too.) Thanks for trying to help. It looks like this solution doesn't work. Maybe there's something wrong with the POST itself. That's what I'm investigating now. – Michael P. Jan 22 '16 at 18:17
  • While I understand your intention, you should reconsider that logic. Node is very large in code base and its community. By narrowing down your results to JUST express, you will find more solutions that pertain to your problem. This will prevent you from sifting through hours worth of articles on node and http servers, that are unrelated to your problem. – Seth Jan 22 '16 at 18:25
  • 1
    You're 100% right. I'll be more mindful of this sort of thing going forward. – Michael P. Jan 22 '16 at 18:25
  • @Seth I am using the same setup in my Express app. I am writing a client using the Electron framework, and trying to send POST requests (using [npm request module](https://github.com/request/request)) using JSON objects for the body of the request. I expected the `app.use(bodyParser.json())` middleware to parse the request, but somehow the parsing seems to be happening in the `app.use(bodyParser.urlencoded({extended:true})` middleware and fails until I change the `extended` option to `false`. I am lost! – Web User Jul 04 '16 at 02:16