session data getting stored every time - javascript

Below is the API that basically stores data in session if not already present then returns an empty JSON, otherwise sends the session data stored corresponding to that mail:
app.use('/session', function(req, res) {
if (req.body.email in req.session) {
console.log("user data already available");
res.send(req.session[req.body.email]);
} else {
req.session[req.body.email] = {};
req.session[req.body.email]["email"] = req.body.email;
req.session[req.body.email]["gender"] = req.body.gender;
req.session[req.body.email]["dbname"] = req.body.dbname;
console.log("user session stored");
res.send({});
}
});
Below is the ajax call that I am making from my application. It is a cross domain call and I have set the response header accordingly.
$.ajax({
url: 'url/session',
type: "POST",
crossOrigin: true,
data: {
"email": "email",
"gender": "all",
"dbname": "dbname"
},
success: function(data) {
console.log("inside session api call success");
console.log(data)
}
});
});
Now the problem is that if I hit the API using postman, it works fine but when I use that in my application, it overwrites the session every time and returns empty json. What am I doing wrong?
edit : Figured out that each time ajax call is happening, past session data gets deleted for all emails ids.session value gets reset but still unable to figure out why this is happening.

Related

How to set up session in vuejs django after successful login?

If login is successful i need to redirect to a login success page and I need to include a session in that.. How can it be possible. I am using html with vue js for front end and back end is django.
This is my vue js script for login.
<script>
logBox = new Vue({
el: "#logBox",
data: {
email : '',
password: '',
response: {
authentication : '',
}
},
methods: {
handelSubmit: function(e) {
var vm = this;
data = {};
data['email'] = this.email;
data['password'] = this.password;
$.ajax({
url: '/login/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if(e.status){
alert("Login Success");
// Redirect the user
window.location.href = "/loginsuccess/";
}
else {
vm.response = e;
alert("failed to login!");
}
}
});
return false;
}
},
});
</script>
So, how can I include session in login successpage.. This is the first time I am doing a work.. Please help me ..
If you are not doing a SPA, you can use the usual way of store sessions, put the session token in a cookie (the server is the responsible of doing when a successful login request happens). The next time the user do a request the cookie will send automatically to the server.
If you are doing a SPA, you can store the session token in the localStorage. In this case, you should configure the ajax calls to set a header with the token or any other way you prefer to send the token to the server.

I need to update/Refresh my JSON Web Token

I need to update/refresh my JSON web token. I have a value of hasPaid that is created and stored inside of my JWT. It works successfully when I login. Because that is when the JWT is created. However, when I pay inside of the application; the JWT isn't updated to reflect that I have paid. And the JWT is reading this data from the database. So i need the JWT to update or refresh and reflect this change.
Here is where my JWT is created:
userSchema.methods.generateJwt = function() {
console.log("I'm creating a JSON WebToken");
console.log(this.hasPaid);
var expiry = new Date();
expiry.setDate(expiry.getDate() + 7);
return jwt.sign({
_id: this._id,
email: this.email,
name: this.name,
hasPaid : this.hasPaid,
exp: parseInt(expiry.getTime() / 1000),
}, "MY_SECRET"); // DO NOT KEEP YOUR SECRET IN THE CODE!
};
Here is my AJAX request where I make the payment. I need it update here:
$.ajax({
url: 'http://localhost:8082/charge',
type: 'POST',
data: {
stripeToken: response.id,
currentUser: user
},
complete: function(response, state, e) {
window.location.assign("video");
return e.localStorage["token"]; // on success of ajax post update JWT
}
});

Array is flattened when it's sent through AJAX jQuery request

I have the following endpoint written in Express, using the body-parser middleware.
app.post("/api/poll/new",api.NewPoll);
api.NewPoll = function(req,res){
if(!req.body) return res.status(400).send("MISSING BODY");
console.log(req.body,typeof(req.body));
if(!req.body.name) return res.status(400).send("MISSING NAME");
if(!req.body.options) return res.status(400).send("MISSING OPTIONS");
//rest of the endpoint goes here
};
The data that the endpoint expects looks like this:
{
"name":"Poller",
"options":[
{
"name":"Jojo's Bizarre Adventure",
"desc":"A great show"
},
{
"name":"Bakemonogatari",
"desc":"A real good show"
},
}
When I send this data through Postman, everything works. req.body.options exists and is an array. However, when I do the exact same thing in a jQuery AJAX call, the result is signficantly different:
var payload = {
name:"Poller",
options:g.newPollInfo
//g.newPollInfo contains the same array
}
$.ajax({
method:"POST",
url:"/api/poll/new",
data:payload,
success:function(data){
console.log(data);
},
error:function(req, status, error){
console.log(req,status,error);
}
});
I get a 400 error, reporting missing Options. The printed req.body looks like this:
{ name: 'Poller',
'options[0][name]': 'Jojo'\s Bizarre Adventure',
'options[0][desc]': 'A great show',
'options[1][name]': 'Bakemonogatari',
'options[1][desc]': 'A real good show' } 'object'
I have never had this problem before. The problem is not in express, as a request through Postman using the same data and it works. The only problem I can think of lies in the fact that the request is made from an iframe serviced through a secure connection, but that doesn't make sense.
I have no idea what causes this error.
According to both these questions, the problem is solved specify the header type on the AJAX Request and stringify.
$.ajax({
method:"POST",
url:"/api/poll/new",
data:JSON.stringify(payload),
contentType:"application/json",
success:function(data){
console.log(data);
},
error:function(req, status, error){
console.log(req,status,error);
}
});

AJAX post data almost saving to the db?

Testing the modules, the AJAX is posting properly in the browser's console.log, and the Node.js/express4 mongoose .save method is saving properly into MongoDB (testing with Postman - REST Client)
For some reason, the AJAX post data has yet to make it to the db, though it accurately logs the data..
$(document).ready(function(){
$('#SubmitBtn').click(function() {
var message = $( "#message" ).val();
console.log(message); // logs as the "user's message"
var AjaxPostData = {'message' : message};
console.log(AjaxPostData); // logs as [object Object]
// make an ajax call
$.ajax({
dataType: 'json',
data: AjaxPostData,
type: 'post',
url:"http://localhost:4200/api/v1/stories",
success: foundAllSuccess,
error: foundAllFailure
});
console.log(AjaxPostData.message); // logs as the "user's message"
});
});
Express4 routing:
var router = express.Router(); // an instance of the express Router
var Story = require('./app/models/story'); // load the mongoose model
router.route('/stories')
// create a story (accessed at POST http://localhost:4200/api/v1/stories)
.post(function(req, res) {
var story = new Story(); // create a new instance of the Story model
story.message = req.body.message; // set the message, from the request
console.log(req.body.message); // logs with Postman, yet the ajax post
// save the story, and check for errors
story.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Story "' + story.message + '" Created' });
});
})
app.use( '/api/v1', router ); // all of the routes are prefixed
Replace data: AjaxPostData,
With data : JSON.stringify(AjaxPostData),
I dont believe the data is being passed correctly and thats why it sends at [Object object]
Turns out that the ajax click event needed e.preventDefault(); or return false;
$('#SubmitBtn').click(function(e) {
e.preventDefault();
// do something
});
$('#SubmitBtn').click(function() {
//do something
return false;
});
Either work in this case..though here's a great post on the differences: event.preventDefault() vs. return false

how to call web service rest based using ajax + jquery

I am calling web service on this url .
here is my code .
http://jsfiddle.net/LsKbJ/8/
$(document).ready(function () {
//event handler for submit button
$("#btnSubmit").click(function () {
//collect userName and password entered by users
var userName = $("#username").val();
var password = $("#password").val();
//call the authenticate function
authenticate(userName, password);
});
});
//authenticate function to make ajax call
function authenticate(userName, password) {
$.ajax({
//the url where you want to sent the userName and password to
url: "",
type: "POST",
// dataType: 'jsonp',
async: false,
crossDomain: true,
contentType: 'application/json',
//json object to sent to the authentication url
data: JSON.stringify({
Ticket: 'Some ticket',
Data: {
Password: "1",
Username:"aa"
}
}),
success: function (t) {
alert(t+"df")
},
error:function(data){
alert(data+"dfdfd")
}
})
}
Response
**
**
It mean that I first call this method then call login method ?
Perhaps the message means that during development, while you are writing and testing the code, use the URL:
http://isuite.c-entron.de/CentronServiceAppleDemoIndia/REST/GetNewAuthentifikationTicket
rather than:
http://isuite.c-entron.de/CentronService/REST/Login
Because you don't need the application id for the development method. You can see from the error message that you are missing the application (gu)id
The guid '61136208-742B-44E4-B00D-C32ED26775A3' is no valid application guid
Your javascript needs to be updated to use new url http://isuite.c-entron.de/CentronServiceAppleDemoIndia/GetNewAuthentifikationTicket as per the backend sode team.
Also, even if you do this, your will not be able to get reply correctly since service requires cross domain configuration entries in web.config. You have to use this reference:http://encosia.com/using-cors-to-access-asp-net-services-across-domains/ and configure server's web.config in a way so that you can call it from cross domain.

Categories

Resources