I make a POST AJAX request:
firebaseAUTH.currentUser.getToken(true).then(function(idToken) {
$.ajax({
// Send token to your backend via HTTPS (JWT)
url: '/auth',
type: 'POST',
data: {token: idToken},
success: function (response) {
var userID = response.userID
firebaseDB.ref('/users/' + userID)
.once('value')
.then(function(snapshot) {
$.post('/members-area/' + userID, snapshot.val(), function(data, status) {
});
});
}
});
});
My handler:
app.use('/members-area/', function(req,res,next) {
console.log(req.body) //works well and gives object
res.render('members-area', { Snapshot: req.body})
})
However, it does not render the page. Why is that and how can I achieve that?
I can't move that function call outside of the success attribute of the AJAX call, as then the decoded userID variable would not be available.
Related
I have a simple login, once user is logged in I have added a call back to run another post so that I have access to the post json to use in my system.
I think the way I have done it is correct however I am getting error
GetData is not defined
Is this the correct way to do this
JavaScript
$scope.LogIn = function () {
$http({
url: "http://www.somesite.co.uk/ccuploader/users/login",
method: "POST",
data: $.param({'username': $scope.UserName, 'password': $scope.PassWord}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
// success
console.log('success');
console.log("then : " + JSON.stringify(response));
GetData();
// location.href = '/cms/index.html';
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});
};
$scope.UserData = function ($scope) {
$scope.UserName = "";
$scope.PassWord = "";
};
$scope.GetData = function () {
$http({
url: " http://www.somesite.co.uk/ccuploader/campaigns/getCampaign",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
// success
console.log('you have received the data ');
console.log("then : " + JSON.stringify(response));
location.href = '/cms/index.html';
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});
};
You need to update your code to be $scope.GetData();.
Currently you are using GetData() which doesn't reference the same method. In fact it is undefined as per the error message.
In server side,I fetch data from database
var sql = require('mssql');
app.get('/api/comments', function(request, response) {
var sqlConfig = {
// Connection string parameters.
}
sql.connect(sqlConfig, function() {
var request = new sql.Request();
var stringRequest = 'select TOP 10 * from comment';
request.query(stringRequest, function(err, recordset) {
if(err) console.log(err);
sql.close();
response.json(recordset);
});
});
});
Then,I fetch the data from server side by AJAX (get method)
_fetchComments() {
jQuery.ajax({
method: 'GET',
url: '/api/comments',
success: (comments) => {
this.setState({ comments })
}
});
I get an error when I get the data by Ajax.
(Uncaught TypeError: this.state.comments.map is not a function)
It seems that the data return is undefined.Instead of fetching database,the code is work if I use static data(hard code) in server side.
I think the problem is the callback function in sql.connect() but I have no idea how to solve it.Does anyone can help?
Error:
The solution is adding dataType: 'json' to the ajax
_fetchComments() {
jQuery.ajax({
method: 'GET',
url: '/api/comments',
dataType: 'json',
success: (comments) => {
this.setState({ comments })
}
});
}
I've been having a problem all day sending json data via ajax to Express.
My ajax looks like this:
$('#saveClause').click(function () {
var username = document.getElementById('postUserName').innerHTML;
var clauseTitle = document.getElementById('modalTitle').innerHTML;
var clauseDescription = document.getElementById('modalDescription').innerHTML;
var clauseText = document.getElementById('modalText').innerHTML;
$.ajax({
url: "/classes/updateAssignment",
type: "post",
dataType: "json",
data: {
username: username,
title: clauseTitle,
description: clauseDescription,
text: clauseText
},
cache: false,
contentType: "application/json",
complete: function () {
console.log("complete");
},
success: function () {
console.log("success");
},
error: function () {
console.log("Process Error");
}
});
});
and my Express Classes routes looks like this:
router.post('/updateAssignment', function (req, res) {
console.log(req.body.username)
console.log(req.body.title);
console.log(req.body.description);
console.log(req.body.text);
res.type('json');
res.send({
some: JSON.stringify({
response: 'json'
})
});
});
I issued a postman post request to the url with this JSON object:
{
"username":"testing",
"title":"123",
"description":"j456",
"text":"seven"
}
and Express logged all the details in the console just fine, so it must be a problem with my ajax request as it's giving me an unexpected token u error but I don't know what's causing it. Any ideas?
Try removing the contentType: "application/json",
If you used postman with no headers, most likely this is causing the parser to fail.
I have the following request handler that would sign in a user with Firebase. Upon successful login, I'd like to redirect the user to another page.
Would I change window.location to another page within the (document).ready() javascript function? Or would I implement the change here, with a res.redirect (that I did try) but nothing happened, I just got back a status code within the console.
app.post('/api/sign-in', function (req, res, next) {
firebase.auth().signInWithEmailAndPassword(req.body.email, req.body.password).then(function (user) {
console.log('a new user has signed in! their e-mail address: ' + user.email + ' | User ID: ' + user.uid)
}).catch(function (error) {
console.log(error)
})
})
Call:
$("#sign-in").on('click', function (event) {
event.preventDefault()
$.ajax({
url: '/api/sign-in',
method: 'POST',
data: {
email: $('#email').val(),
password: $('#password').val()
}
});
});
Like George said, if you are doing a ajax post it won't redirect.
Maybe something like this could help you:
app.post('/api/sign-in', function (req, res, next) {
firebase.auth().signInWithEmailAndPassword(req.body.email, req.body.password).then(function (user) {
res.send({ redirect: '/profile' })
}).catch(function (error) {
console.log(error)
})})
Javascript:
$(document).ready(function () {
$('#sign-in').click(function () {
event.preventDefault()
$.ajax({
url: '/api/sign-in',
method: 'POST',
dataType: 'json',
success: function (data, textStatus, jqXHR) {
if (typeof data.redirect === 'string') {
window.location = data.redirect;
}
}
});
});
});
Hope it can be useful.
I am new to the working with TAPE JS for testing. I have it all setup and working, and it works fine with regular tests. But I am trying to test a unique REST API based product that relies on certain calls to have been made before the next call has the information needed to have a successful call.
So here are the first two calls I am trying to get working:
var SessionId;
test('beginIqsSession', function (assert) {
assert.plan(1);
var requestData = {"ProductDataArray":{"Feid":"GIQNY","AltData":"SaneID:null","Debug":"false","PageId":"1.1"}};
request({
url: 'http://192.168.99.100/Iqs/api.php/beginIqsSession',
method: "POST",
json: requestData
}, function(error, response, json){
if(json.responseDataPayload.SessionId)
{
SessionId = json.responseDataPayload.SessionId;
assert.equal(1,1);
}
});
assert.end();
});
test('validateAddress', function (assert) {
assert.plan(2);
console.log("Retrieving validateAddress response");
var requestData = {"SessionId":SessionId,"ValidateAddressDataArray":{"PropertyStreetNumber":"20671","PropertyStreetName":"mountain vista dr","PropertyCity":"anchorage","PropertyState":"AK","PropertyZipCode":"99577"}};
console.log(SessionId);
request({
url: 'http://192.168.99.100/Iqs/api.php/validateAddress',
method: "POST",
json: requestData
}, function (error, response, body) {
if (!error) {
console.log(body);
}
else {
console.log("error: " + error)
}
});
assert.end();
});
So basically in the code above, I am trying to test beginIqsSession, wait for its response, and store a piece of data from that response that future calls require to be sent in.
in validateAddress you'll see I am trying to pass SessionId in which was returned in the previous call, but because this test is being run at the same time as the previous test, this variable is still empty. How can I make the second call, and all future calls, to wait for the previous call to run?
assert.plan apparently doesn't work in this way.
You could use the Promise API
var SessionId;
let p1 = new Promise((resolve, reject) => {
test('beginIqsSession', function (assert) {
assert.plan(1);
var requestData = {"ProductDataArray":{"Feid":"GIQNY","AltData":"SaneID:null","Debug":"false","PageId":"1.1"}};
request({
url: 'http://192.168.99.100/Iqs/api.php/beginIqsSession',
method: "POST",
json: requestData
}, function(error, response, json){
if(json.responseDataPayload.SessionId)
{
SessionId = json.responseDataPayload.SessionId;
assert.equal(1,1);
resolve(SessionId);
}
});
assert.end();
});
})
p1.then((SessionId) => {
test('validateAddress', function (assert) {
assert.plan(2);
console.log("Retrieving validateAddress response");
var requestData = {"SessionId":SessionId,"ValidateAddressDataArray":{"PropertyStreetNumber":"20671","PropertyStreetName":"mountain vista dr","PropertyCity":"anchorage","PropertyState":"AK","PropertyZipCode":"99577"}};
console.log(SessionId);
request({
url: 'http://192.168.99.100/Iqs/api.php/validateAddress',
method: "POST",
json: requestData
}, function (error, response, body) {
if (!error) {
console.log(body);
}
else {
console.log("error: " + error)
}
});
assert.end();
});
});