My javascript calls a post request from an API. I would like to somehow save the json response and reuse it as authentication to get data.
This is what I have so far...
Post Javascript request:
$(document).ready(function () {
$("#login").click(function () {
console.log("click");
url = "/api/Users/authenticate";
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
s = '{"userName": "' + username + '","userPassword": "' + password + '"}';
callback = function (data) {
alert("User Logged In.");
var response = jQuery.parseJSON(data);
var token = response[3];
sessionStorage.setItem("token",token)
};
callbackerror = function (data) { alert("Error"); };
$.ajax({
type: "POST",
url: url,
data: s,
success: callback,
error: callbackerror,
processData: false,
contentType: 'application/json'
});
});
});
Get Javascript Request:
function loadUsers() {
url = "/api/Users/";
callback = function (data) {
var htmldata = "";
$.each(data, function (i, item) {
htmldata += '<div class="row">' +
'<div class="col-sm-3">' + item.userID + '</div>' +
'<div class="col-sm-3">' + item.userName + '</div>' +
'<div class="col-sm-3">' + item.currentLotUsed + '</div>' +
'<div class="col-sm-3">' + item.carparkid + '</div>' +
'</div>'
});
$("#carparkview").html(htmldata);
};
callbackerror = function (data) { alert("Error"); };
$.ajax({
type: "GET",
url: url,
headers: {
'Authorization': 'Bearer ' + sessionStorage.getItem("token")
},
data: {},
success: callback,
error: callbackerror
});
};
$(document).ready(loadUsers);
My json response:
{
"id": "355e91da-87e7-4c03-a5d0-860ced6cc590",
"username": "Dick123",
"name": "Dickson",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjM1NWU5MWRhLTg3ZTctNGMwMy1hNWQwLTg2MGNlZDZjYzU5MCIsIm5iZiI6MTU0NzgzMzQzNSwiZXhwIjoxNTQ4NDM4MjM1LCJpYXQiOjE1NDc4MzM0MzV9.xkrloD3isYY7XvvAY2KZJODNSwDKFBV30rECEDpMRZo"
}
I am using asp.net and mvc. My code doesn't work and I can't think of a solution to solve this problem. Please give me some advice, I need help.