Skip to content

Instantly share code, notes, and snippets.

Created March 6, 2018 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/3a96bb30fd29a5c6852b77acac9963df to your computer and use it in GitHub Desktop.
Save anonymous/3a96bb30fd29a5c6852b77acac9963df to your computer and use it in GitHub Desktop.
[NodeJS + MongoDB] Mongoose/BodyParser not correctly accepting urlencoded POST requests
var mongoose = require('mongoose');
//Defining a schema for database entries.
var itemSchema = new mongoose.Schema({
name: String,
quantity: Number
});
//Exporting the model (containing the schema) to use as a module in other files
module.exports = mongoose.model('Item', itemSchema);
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var Item = require('./item');
//Express Application is the main component of the web app.
//Used to define routes, listen on http connections, perform routing for requests, and more
var app = express();
//Enable the body-parser package for use in our application
app.use(bodyParser.urlencoded({
extended:true}));
app.use(bodyParser.json());
var dbUrl = "mongodb://localhost:27017/testdatabase";
var port = 3000;
//Connecting to the Mongo Database
var connection = mongoose.connect(dbUrl);
//Router are similar to "mini applications" - capable only of middleware and routing
//Every express application has a built in app router.
//Routers behave like middleware and can be .use()'d by the app or in other routers
var router = express.Router();
router.use(function(req, res, next){
console.log("Request Made");
next();
});
//Creating a route for '/' to return a JSON object
router.get('/', function(req, res) {
res.json({ message: "response!" })
});
//Creates a new route within the already created router for '/'
var itemRouter = router.route('/items');
//Creating an endpoint for POSTS /api/beers
itemRouter.post(function(req, res){
console.log(req.body);
var newItem = new Item();
newItem.name = req.body.name;
newItem.quantity = req.body.name;
//Code below works with JSON formatted inputs.
//newItem.quantity = req.body[1].value;
//newItem.quantity = req.body[1].value;
//Saves the new item to the database
newItem.save(function(err){
if(err) {
res.send(err);
}
//sends a response
res.json({
message: 'Item added to the database!',
data: newItem
});
});
});
//Creating the endpoint for GET requests on '/api/items'
itemRouter.get(function(req, res){
item.find(function(err, items) {
if(err){
res.send(err);
}
res.json(items);
});
});
//Creating a new route to add items to our
//Register all previously defined routes with the prefix '/api'
app.use('/api', router);
app.listen(port);
console.log("Server listening on port " + port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment