Sunday 28 May 2017

Express JS POST Request Failing

I am trying to write code to create a mongodb entry using express.js. However, when I test my code with a cURL request, I get the error "empty response from server".

Here is my express.js code:

var express = require('express');
var router = express.Router();
var http = require('http');
var url = require('url');
var util = require('util');
var bodyParser = require('body-parser')
var ObjectID = require('mongodb').ObjectID;

router.use(bodyParser.json());
router.use(bodyParser.urlencoded({extended: true}));

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_db');

var channelSchema = mongoose.Schema({
  name: String,
  verified: String,
  private: String,
  channelID: String,
  handle: String,
  subscribers: String
});

var Channel = mongoose.model("Channel", channelSchema);
router.post('/createChannel', bodyParser, function(req, res, next) {
    if(!req.body) return res.send(400);
    var objID = new ObjectID();

    var newChannel = new Channel({
      name: req.body["name"],
      verified: req.body["verified"],
      private: req.body["private"],
      channelID: objID,
      handle: req.body["handle"],
      subscribers: req.body["subscribers"]
     });

    newChannel.save(function(err, point){
      if(err) res.send(500);
      else res.send(200);
    });

});

module.exports = router;

I do not understand why the request is failing...it always times out. Does it have something to do with the HTTP response that I am giving?



via Aidan Kaiser

No comments:

Post a Comment