Skip to content

POST Http Issue #51

@peweet

Description

@peweet

I am stuck on the CRUD part of the mean machine book. Whenever I try create a User through Postman it times out and doesn't get any response. However the code compiles and executes and the page exists when I go to localhost:8080. It just doesn't pass the POST request

The code:
// BASE SETUP
// ======================================

//grab the package we need.

var mongoose = require('mongoose');
//replaced connect with createConnetion
mongoose.createConnection('mongodb://localhost/db_name');

// BASE SETUP
// ======================================

// :@jello.modulus....
// CALL THE PACKAGES --------------------
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser'); // get body-parser
var morgan = require('morgan'); // used to see requests
var mongoose = require('mongoose'); // for working w/ our database
var port = process.env.PORT || 8080; // set the port for our app

var User = require('../restful-app/models/user');
//connect to our database (hosted on modulus.io)
mongoose.connect('mongodb://:@jello.modulusmongo.net:27017/byq7Ewim');

// APP CONFIGURATION ---------------------
// use body parser so we can grab information from POST requests
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// configure our app to handle CORS requests
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,
Authorization');
next();
});

// log all requests to the console
app.use(morgan('dev'));

// ROUTES FOR OUR API
// =============================

//route middleware and first route are here

//on routes that end in /users
// ----------------------------------------

var apiRouter = express.Router();
// get an instance of the express Router

apiRouter.route('/users')

//create a user (accessed at POST http://localhost:8080/api/users)
// A post route is created for our application

.post(function(req, res){
//create a new interface of the user model
var user = new User();

//set the users information (comes from the request)
user.name = req.body.name;
user.username = req.body.username;
user.password = req.body.password;

//save the user and check for errors

user.save(function(err) {

if(err) {
//duplicate entry
if(err.code= 11000)
return res.json({ success: false, message: 'A user with that\ username already exists. '});
else
return res.send(err);

}
            res.json({message: 'User created'});
          });

})

// middleware to use for all requests
apiRouter.use(function(req, res, next) {
// do logging
console.log('Somebody just came to our app!');

 // we'll add more to the middleware in Chapter 10

// this is where we will authenticate users

next(); // make sure we go to the next routes and don't stop here
});

// test route to make sure everything is working
// (accessed at GET http://localhost:8080/api)
apiRouter.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});

//more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------

// all of our routes will be prefixed with /api
app.use('/api', apiRouter);

// more routes for our API will happen here

// basic route for the home page
app.get('/', function(req, res) {
res.send('Welcome to the home page!');
});

// get an instance of the express router
var apiRouter = express.Router();

// test route to make sure everything is working
// accessed at GET http://localhost:8080/api
apiRouter.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});

// more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', apiRouter);

// START THE SERVER
// ===============================
app.listen(port);
console.log('Magic happens on port ' + port);

The User.js schema code.

// grab the packages that we need for the user model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');

// user schema
var UserSchema = new Schema({
name: String,
username: { type: String, required: true, index: { unique: true }},
password: { type: String, required: true, select: false }
});

// hash the password before the user is saved
UserSchema.pre('save', function(next) {
var user = this;
16
// hash the password only if the password has been changed or user is new
if (!user.isModified('password')) return next();

// generate the hash
bcrypt.hash(user.password, null, null, function(err, hash) {
if (err) return next(err);

// change the password to the hashed version
user.password = hash;
next();
});
});

// method to compare a given password with the database hash
UserSchema.methods.comparePassword = function(password) {
var user = this;

return bcrypt.compareSync(password, user.password);
};

// return the model
module.exports = mongoose.model('User', UserSchema);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions