alex
alex

Reputation: 1

POST http://localhost:3000/api/signup 400 (Bad Request)

I'm new to MEAN stack and having trouble with sending registration data through http.post.

Here is my server code:

var express = require('express'),
  bodyParser = require('body-parser'),
  methodOverride = require('method-override'),
  errorHandler = require('express-error-handler'),
  morgan = require('morgan'),
  routes = require('./routes'),
  api = require('./routes/api'),
  http = require('http'),
  path = require('path'),
  usersController = require('./public/js/userscontroller.js');

var app = module.exports = express();

var mongoose = require('mongoose');
var connection = require('./config/database')(mongoose);
var models = require('./models/models')(connection);
var cons = require('consolidate');


/**
 * Configuration
 */

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(express.static(path.join(__dirname, 'public')));

var env = process.env.NODE_ENV || 'development';

// development only
if (env === 'development') {
  app.use(errorHandler());
}

// production only
if (env === 'production') {
  // TODO
}


/**
 * Routes
 */

// serve index and view partials
app.get('/', routes.index);
app.get('/partials/:name', routes.partials);

// JSON API
app.post('/api/signup', api.signup);

// redirect all others to the index (HTML5 history)
app.get('*', routes.index);


/**
 * Start Server
 */

http.createServer(app).listen(app.get('port'), function () {
  console.log('Express server listening on port ' + app.get('port'));
});

Here is my api:

/*
 * Serve JSON to our AngularJS client
 */
var User = require('../models/user');


exports.name = function (req, res) {
  res.json({
    name: 'Bob'
  });
};


exports.signup = function (req, res, next){
    console.log("in signup in API");
    if(!req.body.username || !req.body.password){
        return res.status(400).json({message: 'Please fill out all feelds'});
    }
    var user = new User();
    user.username = req.body.username;
    user.setPassword(req.body.password);
    console.log("after set password");
    user.save(function(err, result) {
        if(err){return next(err); }
        res.json(result);
    });
};

And here is my client side JS app.js:

'use strict';

// Declare app level module which depends on filters, and services

angular.module('myApp', [
  'myApp.controllers',
  'myApp.filters',
  'myApp.services',
  'myApp.directives',
  'ngResource'
]).
config(function ($routeProvider, $locationProvider) {
  $routeProvider.
    when('/view1', {
      templateUrl: 'partials/partial1',
      controller: 'usersController'
    }).
    when('/view2', {
      templateUrl: 'partials/partial2',
      controller: 'usersController'
    }).
    otherwise({
      redirectTo: '/view1'
    });

  $locationProvider.html5Mode(true);
}).
factory('auth', ['$http', '$window', function($http, $window, auth){
  var auth = {};

  //saves token
  auth.saveToken = function (token){
    $window.localStorage['nicerpg-token'] = token;
  };

  //Attempts to register the user
  auth.signup = function(user){
    console.log(user);
    $http({
      method: "POST",
      url: "/api/signup",
      headers: {"Content-Type": "application/json"}
    });
    // return $http.post('/api/signup', user).success(function(data){
    //   //auth.saveToken(data.token);
    // });
  };

  return auth;
}]);

Finally, here is the controllers.js:

'use strict';

/* Controllers */

angular.module('myApp.controllers', []).
  controller('AppCtrl', function ($scope, $http) {

    $http({
      method: 'GET',
      url: '/api/name'
    }).
    success(function (data, status, headers, config) {
      $scope.name = data.name;
    }).
    error(function (data, status, headers, config) {
      $scope.name = 'Error!';
    });

  }).
  controller('usersController', ['$scope', '$resource', 'auth', function ($scope, $resource, auth) {
    // write Ctrl here
    var User = $resource('/api/users');
    var Signup = $resource('/signup');

      //Gets all the users
    User.query(function(results) {
      //console.log(results);
      $scope.users = results;
    });

    $scope.signup = function(){
      auth.signup($scope.registerform);

      // .error(function(error){
      //   console.log(error);
      //   $scope.error = error;
      // }).then(function(){
      // });

      User.query(function(results) {
        // console.log(results);
        $scope.users = results;
      });
      $scope.registerform = '';

    };

  }]);

When i put localhost:3000/api/signup into my browser I get the expected missing fields response; However, when i try running the code with the http.post, it returns 400 bad request. I've tried changing the http header content-type several times with no luck, along with many other fruitless attempts at solution. Please help me :(

Thank you!

Upvotes: 0

Views: 28355

Answers (4)

Daner
Daner

Reputation: 91

instead of sending it as {application/json} send it as {text/plain}

Upvotes: 0

Hardik Sharma
Hardik Sharma

Reputation: 29

Here is the mistake you have made while writing your POST request body, which is going to hit your API.

Solution: In your app.js file, under auth.signup function in $http function replace your request JSON with the below-written JSON

{
  method: "POST",
  url: "/api/signup",
  headers: {"Content-Type": "application/json"},
  body: { 
        "username": "Your_username",
        "password": "Your_password" 
    }
}

Upvotes: 0

ravichandra reddy
ravichandra reddy

Reputation: 219

specify the data object as below

 data: {
    username: "demo",
    password: "password"
 }

This should fix your issue.But you auth method is not handling the ajax call. Incase the call fails due to wrong credentials you controller still goes ahead and does User.query,which is not expected behaviour.

Upvotes: 0

Mary
Mary

Reputation: 134

You haven't specified the post body. Take a look into the AngularJS http post documentation for more details.

Upvotes: 0

Related Questions