I need to login on my rest service. I parse the json and the data seems correct. But it doesn't work.
First I load the form data with the names: 'username' and 'wachtwoord' Then I parse it to a json, and send it to my rest service. But every time it fails.
POST request
$(document).ready(function() {
$('#doLogin').submit(function() {
var $inputs = $('#doLogin :input');
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
var data = {}
var Form = this;
//Gathering the Data
//and removing undefined keys(buttons)
$.each(this.elements, function(i, v){
var input = $(v);
data[input.attr("name")] = input.val();
delete data["undefined"];
});
$.ajax({
cache: false,
url : "http://localhost:666/api/login/",
type: "POST",
dataType : "json",
data: JSON.stringify(data),
}).fail(function (jqXHR, textStatus) {
alert("Login Failed");
}).done(function (data) {
alert(data.token);
});
});
});
REST server
var jwt = require('jsonwebtoken');
var express = require('express');
var router = express.Router();
var User = require('./model/users');
var privateKey = "1fjdu89379edfasf73";
router.post('/', function (req, res) {
var name = req.body.username;
var pass = req.body.wachtwoord;
User.findOne({username: name, wachtwoord: pass},
function (err, user) {
if (user) {
var username = req.body.username;
var token = jwt.sign({username: username}, privateKey, {expiresIn: 60 * 60 * 24});
res.status(200).json({token: token});
} else {
res.status(500).json("Username or Password incorrect!");
}
});
});
module.exports = router;
</div>