我有一个表单,我将其作为POST请求提交...
<form onSubmit={this.handleLogin.bind(this)} action="/" method="post">
<div>
<label>Username:</label>
<input type="text" name="username"/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password"/>
</div>
<div>
<input type="submit" value="Log In"/>
</div>
</form>
所以onSubmit
我打电话handleLogin
试图提交表单......
handleLogin(){
fetch('http://localhost:8080', {
method: 'post',
body: JSON.stringify({
username: this.state.username,
password: this.state.password
})
})
}
表单正在提交给我的服务器,POST
应该获取请求,如下所示......
app.post('/', function(req, res, next) {
console.log("post");
passport.authenticate('register', function(err, user, info) {
console.log("authenticate");
})(req, res, next);
});
由于某种原因,user
为空且info
为false,表示未正确调用护照。默认情况下,护照js需要用户名和密码,因此我不确定是否应该通过POST请求传递用户名和密码。
以下是passport
的其余代码......
passport.use('register', new LocalStrategy({
passReqToCallback : true
},
function(req, username, password, done) {
process.nextTick(function(){
//find user in DB with this username
User.findOne({'username': username}, function(err, user) {
if (err) {
console.log("Error in registration: " + err);
}
//If user already exists in DB
if (user) {
console.log("User already exists");
return done(null, false, req.flash('message', 'User Already Exists'));
}
else {
//if user does not exist, create it
var newUser = new User();
newUser.username = username;
newUser.password = newUser.generateHash(password);
//console.log("hgeeer");
//save the user
newUser.save(function(err) {
if (err) {
console.log('Error in Saving user: '+err);
throw err;
}
console.log("User Registered");
return done(null, newUser);
});
}
})
})
}));
这样做的正确方法是什么?
答案 0 :(得分:1)
我认为您没有向passport
尝试在username
password
和Strategy
passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',//changed accordingly as `username`
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
您可以参考here
答案 1 :(得分:0)
passport-local
策略对请求正文使用urlencoded
格式。在文档中,您需要指定使用urlencoded的中间件:
app.use(bodyParser.urlencoded({ extended: false }));
当您使用JSON.stringify()作为参数时,提取api将使用默认的内容类型标头作为text
。为了将其正文以urlencoded格式发送,您可以:
fetch(url, {
...
//you don't have to specify the conten-type header, because fetch will use urlencoded format automatically when you use URLSearchParams api
body: new URLSearchParams(your_json_data_here)
});