POST http:// localhost:3000 / api / signup 400(错误请求)

时间:2016-04-29 06:14:27

标签: javascript angularjs json node.js http-headers

我是MEAN堆栈的新手,无法通过http.post发送注册数据。

这是我的服务器代码:

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'));
});

这是我的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);
    });
};

这是我的客户端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;
}]);

最后,这是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 = '';

    };

  }]);

当我将localhost:3000 / api / signup放入浏览器时,我得到了预期的缺失字段响应;但是,当我尝试使用http.post运行代码时,它返回400错误请求。我已经尝试多次更改http标头内容类型,没有运气,以及许多其他无效的尝试解决方案。请帮帮我:(

谢谢!

3 个答案:

答案 0 :(得分:0)

您尚未指定帖子正文。有关详细信息,请查看AngularJS http post文档。

答案 1 :(得分:0)

指定数据对象,如下所示

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

这应该可以解决您的问题。但是您的auth方法不处理ajax调用。由于控制器仍在进行的错误凭据而导致调用失败并且执行User.query,这不是预期的行为。

答案 2 :(得分:0)

这是您在编写 POST 请求正文时所犯的错误,这会影响您的 API。

解决方案:在您的 app.js 文件中,在 $http 函数中的 auth.signup 函数下,将您的请求 JSON 替换为下面编写的 JSON

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