我试图在身份验证失败时传递
JSON消息,在LocalStrategy中使用完成的回调,但是我所得到的只有401和“未授权”字符串在响应中.
var express = require('express'); var bodyParser = require('body-parser'); var passport = require('passport'); var LocalStrategy = require('passport-local').Strategy; var app = express(); app.use(bodyParser.json()); app.use(passport.initialize()); passport.serializeUser(function(user,done) { done(null,user.email); }); var strategy = new LocalStrategy({ usernameField: 'email' },function (email,password,done) { if (email === 'test@gmail.com' && password === 'pass') { return done(null,{ email: 'test@gmail.com' }); } else { // never get this json object on the client side when posting invalid credentials return done(null,false,{ message: 'invalid email or password' }); } } ); passport.use(strategy); app.post('/login',passport.authenticate('local'),function(req,res) { console.log(req.user); res.json(req.user); }); app.get('/',res) { res.json({ message: 'hello!' }); }); var server = app.listen(3000,function() { console.log('api is listening on ',server.address().port); });
的package.json
{ "name": "passport_example","version": "1.0.0","description": "","main": "app.js","scripts": { "test": "echo \"Error: no test specified\" && exit 1" },"author": "","license": "ISC","dependencies": { "body-parser": "^1.13.3","express": "^4.13.3","passport": "^0.2.2","passport-local": "^1.0.0" } }
我究竟做错了什么?