岗位http://localhost:3000/api/signup400(错误请求)
POST http://localhost:3000/api/signup 400 (Bad Request)
我是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标头内容类型,但都没有成功,还有许多其他解决方案的尝试都没有成功。请帮帮我:(
谢谢!
您尚未指定帖子正文。查看AngularJShttp文章文档以了解更多详细信息。
将数据对象指定为以下
data: {
username: "demo",
password: "password"
}
这应该可以解决您的问题。但是auth方法不处理ajax调用。如果由于凭据错误导致调用失败,则控制器仍会继续并执行User.query,这不是预期的行为。
以下是您在编写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"
}
}
而不是以{application/json}发送,而是以{text/plain}
相关文章:
- Node.js v6.2.0类扩展不是函数错误
- Jquery菜单操作不稳定,定位不正确,存在一般错误
- document.open/document.write没有正确地清除chrome中的文档——这是chrome的错误吗
- 试图在引导模式内动态生成图表,得到offsetWidth错误
- 为什么会出现错误;未捕获的类型错误:undefined不是函数;
- 我如何修复包含在captcha的addthis中的错误
- 同样,同样的错误'ahorcado.js:26未捕获类型错误:无法读取属性'beginPath'
- 节点是否需要模块传递带有方括号的arg?这是个错误吗
- Webpack/Rect:遵循egghead.io教程,但出现错误:您可能需要一个合适的加载程序来处理此文件类型
- CKFinder 3为所选文件返回错误的URL
- 同位素库错误:未捕获错误无布局模式包装生产线8
- 铬:“;未捕获的语法错误:意外的标记:"
- 如何通过自己获得Chrome扩展的用户反馈/错误报告
- 相位器状态未捕获参考错误
- /undefined在我的404错误日志中多次出现
- Javascript未捕获语法错误意外的标识符错误
- javascript:如何在antlr生成的Lexer中进行错误处理
- Angularjs工厂注入错误
- 可以设置“;文件名"发生错误时显示的内联脚本标记的
- 岗位http://localhost:3000/api/signup400(错误请求)