请有人帮我在这里找到问题:
当我尝试发布username
和password
时,我总是收到错误消息:
requester.js:6211 POST http://localhost:7000/api/login 403 (Forbidden)send @ requester.js:6211(anonymous function) @ requester.js:4811dispatch @ jquery.min.js:3i @ jquery.min.js:3
requester.js:1056 Defining mode
我根本不知道这里有什么问题。 这是post man请求屏幕截图:
这是我的api文件:
var User = require('../models/user');
var config = require('../../config');
var secretKey = config.secretKey;
var jsonwebtoken = require("jsonwebtoken");
function createToken ( user ) {
var token = jsonwebtoken.sign({
_id : user.id,
name : user.name,
username: user.username
}, secretKey, {
expiresIn : "1440m"
})
return token;
}
module.exports = function( app, express ) {
var api = express.Router();
api.post('/signup', function( req, res ) {
var user = new User({
name : req.body.name,
username : req.body.username,
password : req.body.password
});
user.save( function( err ) {
if( err ) {
res.send( err );
return;
}
res.json({message : "User has been created!"});
});
api.get('/users', function( req, res ) {
User.find({}, function( err, users ) {
if( err ) {
res.send( err );
return;
}
res.json( users );
})
});
api.post('/login', function( req, res ) {
User.findOne({
username : req.body.username
}).select('password').exec(function( err, user ) {
if( err ) throw err;
if(!user) {
res.send({ message : "User doesnt Exist!"})
} else if( user ) {
var validPassword = user.comparePassword( req.body.password );
if(!validPassword) {
res.send({ message : "Invalid Password"});
} else {
var token = createToken( user );
res.json({
success : true,
message : "Successfuly loged In!",
token : token
})
}
}
})
})
});
//middleware
api.use(function(req, res, next) {
console.log("Somebody just came to our app!");
var token = req.body.token || req.param('token') || req.headers['x-access-token'];
// check if token exist
if(token) {
jsonwebtoken.verify(token, secretKey, function(err, decoded) {
if(err) {
res.status(403).send({ success: false, message: "Failed to authenticate user"});
} else {
req.decoded = decoded;
next();
}
});
} else {
res.status(403).send({ success: false, message: "No Token Provided"});
}
});
//Destination B
api.get("/", function( req, res ) {
res.json("Hello World!");
})
return api;
}
答案 0 :(得分:2)
路线应该是' api / signup'而且不仅仅是' /注册'。
路线定义不对。而不是:
api.post('/signup', function( req, res ) {
...
api.get('/users', function( req, res ) {
})
})
它应该是:
api.post('/signup', function( req, res ) {
...
})
api.get('/users', function( req, res ) {
...
})