admin管理员组

文章数量:1387277

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!

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!

Share Improve this question asked Apr 29, 2016 at 6:14 alexalex 11 gold badge1 silver badge3 bronze badges 1
  • So the bad request you recevie from the POST has no body with {message: 'Please fill out all feelds'}? Cause It seems normal from your backend code that you receive a 400 with that call – rick Commented Apr 29, 2016 at 6:32
Add a ment  | 

4 Answers 4

Reset to default 0

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

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.

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" 
    }
}

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

本文标签: javascriptPOST httplocalhost3000apisignup 400 (Bad Request)Stack Overflow