我是javascript的新手。我开始了一个小项目,我想对用户进行身份验证。为此我一直在使用Passport本地策略。但是我在登录按钮上发送的帖子请求给了我错误代码400即错误请求。我我不知道我做错了什么。我搜索过类似的问题,但无法得到满意的答案。下面是代码片段。
的login.html
<md-content layout-margin class="center-form">
<section class="md-whiteframe-7dp" flex>
<div flex layout="column" layout-padding layout-margin>
<form method="post" name="loginForm" layout="column">
<md-input-container>
<label>Email</label>
<input ng-model="user.email" id="user" type="email" ng-pattern="/^[A-z]+[a-z0-9._]+@[a-z]+.[a-z.]{2,5}$/" required>
</md-input-container>
<md-input-container>
<label>Password</label>
<input ng-model="user.password" id="password" name="password" type="password" required>
</md-input-container>
<md-button type="submit" ng-disabled="loginForm.$invalid" ng-click="login(user)" class="md-raised md-primary">Login</md-button>
</form>
</div>
</section>
Login.js
app.controller('LoginCtrl',function ($scope,$http) {
$scope.login=function(user){
console.log(user);
$http.post('/login',user)
.success(function (response) {
console.log(response);
})
}
});
Server.js
//Require Modules
var express=require("express");
var config = require('./config');
var path = require('path');
var routes=require('./routes');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer(); // for parsing multipart/form-data
var passport=require('passport');
var LocalStrategy=require('passport-local').Strategy;
var cookieParser= require('cookie-parser');
var session=require('express-session');
//Init Express App
var app=express();
//Express sessions
app.use(session({
secret:"this is the secret key",
resave:true,
saveUninitialized:false
}));
//Cookie Parser
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());
/*Use Middleware (Between header to hTTP actions)*/
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
//passport startegy
passport.use(new LocalStrategy(function(username,password,done){
console.log("username:"+username);
console.log("password:"+password);
return done(null,false,{message:'unable to login'});
}));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
done(null, id);
});
// serve the static public files
app.use(express.static(path.join(__dirname, '../public')));
app.use('/',routes);
Route.js
var express=require('express');
var router=express.Router();
var passport=require('passport')
router.post('/login',passport.authenticate("local"),function(req,res){
console.log("Logged In");
console.log(req.body);
});
module.exports=router;
我已经阅读了Passport js的文档但是如果有人可以用简单的术语解释为什么在登录点击时发生了400 Bad请求,那对我来说会更有用。我已点击登录按钮发出了帖子请求。
答案 0 :(得分:0)
如果您的表单字段不是默认值username
和password
,就像它们不是默认值一样,您需要提供包含passport-local
字段名称的选项,如所述{{3 }}。否则,由于缺少登录信息,您将in the documentation。