Reputation: 1413
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 + " . . .");
});
Upvotes: 1
Views: 74
Reputation: 10464
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.
Upvotes: 1
Reputation: 119
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.
Upvotes: 1