Javascript Object Undefined - Jquery + Node JS - javascript

I'm facing this problem and I'm a newbie with Javascript and NodeJS, below I have this code at my Route on /update/:id
controller.save = (req, res) => {
const data = req.body
const name = req.body.name
const cpf = req.body.cpf
req.getConnection((err, connection) => {
const query = connection.query(
`INSERT INTO clientes(Nome, CPF)
VALUES('${name}','${cpf}')`,
data,
(err, clientes) => {
res.json(clientes)
}
)
})
}
and I have a form that have a Button called "Update", when I click , the AJAX made this .
$(document).on("click", ".update", function() {
var user_id = $(this).attr("id")
$.ajax({
url: "/update/" + user_id,
method: "GET",
dataType: "json",
success: function(to) {
alert(to)
}
})
})
I'm receive a alert [Object Object], when I go to my Network response I have this:
[{"ID":5,"Nome":"tobiaas","CPF":"107"}]
when I change alert to alert(to.Nome), I receive a alert Undefined
I don't wanna use .map, because i thing that this is a simple way to made work .

You are receiving an array as the response, Array.Nome does not exists, your output is normal.
You need to get the item with response[0] or response.pop() to access it:
success: function(response) {
const to = response[0]
alert(to.Nome)
}
For more info on javascript array access, see W3School

Related

why my sessionStorage gives { 'object Object': '' }

I have a query I'm passing data from one page to other using local storage. after that i take that data and i make a string . Then i pass that json string to sessionstorage to use as data for my ajax request. but i'm always getting this data as { 'object Object': '' }.
my code ,
const parsedData = JSON.parse(localStorage.getItem('myData'));
console.log(parsedData,"parsedData");
parsedData.data.rows.forEach((result, idx) => {
var a = result.master_id;
var b = result.session_name;
console.log(a,b,"a","b")
var userData = {"pid":a,"session" :b};
console.log( userData ,"userData");
sessionStorage.setItem('user', JSON.stringify(userData));
................. then i access this data in another function,
function graphApi(){
const apiValue = (sessionStorage.getItem('user'));
console.log(apiValue,"apivalue new")
/*var dat ={
"pid":"WEB506",
"session":"WEB506_09092021_M1_S2.csv"
};*/
$.ajax({
type: "POST",
data: apiValue ,
url: "http://localhost:5000/file",
success: function (data) {
console.log(data)
},
error: function(err){
alert(err);
}
Plese help, im stuck with for some time now.
in addition, this is my controller api,
File: async (req, res, next) => {
console.log('---------------');
console.log( req.body); this is where i get { 'object Object': '' }
console.log('---------------');
try{
if(!req.body){
throw new Error("sorry no data, error occured")
}
const {pid, session} = req.body;
const user = await models.graph_data.findAndCountAll({
attributes: [
"document"
],
You're consoling the whole arrayof objects not a single object
try
console.log(data.pid) or console.log(data.session)
Try clearing your sesionStorage and try again. The code
{ 'object Object': '' }
is a sign that you used a reference value eg JSON object as a key.
However, your code doesn't seem to do that.
Try clearing your sessionStorage and try again

firebase cloud function: updating a field in firestore by calling an api [duplicate]

Almost there, but for some reason my HTTP post request isn't firing and eventually the function timesout. Completely beside myself and posting my code to see if anyone picks up on any noob moves that I'm completely missing. NOTE: the database write completes so I'm assuming that the HTTP Post request isn't firing, is that a safe assumption? Or JS is a different beast?
exports.stripeConnect = functions.https.onRequest((req, res) => {
var code = req.query.code;
const ref = admin.database().ref(`/stripe_advisors/testing`);
var dataString = `client_secret=sk_test_example&code=${code}&grant_type=authorization_code`;
var options = {
url: 'https://connect.stripe.com/oauth/token',
method: 'POST',
body: dataString
};
function callback(error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
}
}
request(options, callback);
return ref.update({ code: code });
});
I understand that you want to POST to https://connect.stripe.com/oauth/token by using the request library and, on success, you want to write the code value to the database.
You should use promises, in your Cloud Function, to handle asynchronous tasks. By default request does not return promises, so you need to use an interface wrapper for request, like request-promise
Therefore, the following should normally do the trick:
.....
var rp = require('request-promise');
.....
exports.stripeConnect = functions.https.onRequest((req, res) => {
var code = req.query.code;
const ref = admin.database().ref('/stripe_advisors/testing');
var dataString = `client_secret=sk_test_example&code=${code}&grant_type=authorization_code`;
var options = {
url: 'https://connect.stripe.com/oauth/token',
method: 'POST',
body: dataString
};
rp(options)
.then(parsedBody => {
return ref.update({ code: code });
.then(() => {
res.send('Success');
})
.catch(err => {
console.log(err);
res.status(500).send(err);
});
});

Node.js MongoDB updating document expects object, gets array

I'm building my first app using mongodb and node.js and I've come across a brick wall. When i try to .update() or .updateMany() my server comes back with:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): MongoError: Wrong type for 'q'. Expected a object, got a array.
Now the thing is, my code worked before and I have managed to insert an array of about 150 objects into my database. (When i first did this i used .insert() instead of .update(), but now neither works.)
Here's the exact code I'm using to first store an array of objects, and then .update() my database.
Store the array (I am using an external API for this):
var all = [];
$("#update").click(function(){
$.ajax({
type: "GET",
dataType: 'JSON',
url: 'some valid url',
success: function (result){
$.each(result, function(i, item) {
var obj = {
"name" : item['name'],
"id" : item['id'],
"count" : 0
};
all.push(obj);
});
}
});
});
Send to my router.js to be processed:
$('#sendupdate').click(function(){
var jsonstring = JSON.stringify(all);
console.log(jsonstring);
$.ajax({
type: "POST",
dataType: "JSON",
contentType: "application/json",
data: jsonstring,
url: "/s",
success: function(response) {
console.log('Successfully Updated');
}
});
});
});
and finally here's what my router.js does to the received data:
router.post('/s', function(req, res){
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/someDB';
MongoClient.connect(url, function(err, db){
if(err){
console.log('unable to connect to the server', err);
} else {
console.log('connected');
var collection = db.collection('someCollection');
var data = req.body;
console.log('data collected');
console.log(data);
collection.updateMany(data, data, {upsert:true});
}
});
});
Now I know I could loop through the array and make a request for each object, but that feels like I'll be using too much resources, especially knowing that I will need a similar function later on for most users that enter my site.
What else could I do to update the database with so many new objects? I understand that mongodb expects to receive an object, but I don't understand why it worked before when the data received was always an array of objects.
Thank you in advance and I hope someone can shed some light on this for me.
________________________________________
EDIT: I have come up with a temporary solution, I'm still unsure on how good it is but if anyone has any ideas on how to improve this please do let me know.
Here's what I've changed, for anyone having a similar issue:
Instead of trying to update an array with an array I've used a for loop to loop through the array[i] and update each object individually. It happens server-side and is probably not the best solution but it works for now.
Here's the changed code:
router.post('/s', function(req, res){
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/someDB';
MongoClient.connect(url, function(err, db){
if(err){
console.log('unable to connect to the server', err);
} else {
console.log('connected');
var collection = db.collection('someCollection');
var data = req.body;
console.log('data collected');
var i;
for(i = 0; i <= data.length; ++i){
collection.update(data[i], {$set:data[i]}, {upsert:true});
}
}
});
});

Issue with rendering page after performing delete function

exports.deleteItem = function (req, res)
{
var query = req.params.id;
var cart = req.session.items;
var index;
_.each(cart,function (ticket)
{
if(ticket.id === query)
{
index = cart.indexOf(ticket);
cart.splice(index,1);
}
return res.redirect(303, '/cart');
});
};
I am using this function in my routes to perform a delete operation. It works for the first few items on my list, then suddenly stops and gives me the error "Can't set headers after they are sent."
$(document).ready(function() {
$('.delete-from-cart').click(function(event)
{
$target = $(event.target);
$.ajax({
type: 'DELETE',
url: '/cart/remove/' + $target.attr('data-item-id'),
data: {
_csrf: $target.attr('data-csrf')
},
success: function(response)
{
$target.parent().parent().remove();
Materialize.toast('Ticket Removed', 4000);
window.location.href = '/cart';
},
error: function(error)
{
Materialize.toast('Error', 4000);
console.log(error);
}
});
});
});
A single request was made, which means a single response should occur.
When you execute the _.each function I'm guessing that it works if there is one item but fails when there are multiple? This is because you are trying to send multiple responses when only one is permitted.
A good explanation for this can be found here: Error: Can't set headers after they are sent to the client

RESTful login using ajax and node.js

I'm struggling with a rather simple approach to login to a server and later on to ensure that I'm still logged in, I'm sending a GET request to receive my user name. I'm using a little node.js server and a single page object using JQuery.
// prints User name to the console if logged in
function getUserName() {
$.ajax({
url: "http://localhost:4730/login",
type: "GET",
dataType: "json",
success: function (resJson) {
$.each(resJson, function (i, userName) {
console.log(userName);
});
},
error: function (xhr, status) {
console.log("Sorry, there was a problem!");
}
});
}
// login a known user
function login(name, password) {
var userData = {
name: name,
password: password
};
$.ajax({
url: "http://localhost:4730/login",
type: "POST",
dataType: "json",
data: userData,
error: function (xhr, status) {
console.log("Sorry, there was a problem!");
},
complete: function (xhr, status) {
console.log(xhr);
}
});
}
My server (node.js) is generating a dummy user id and checks this one when the next GET request arrives.
// Checks if the user is logged in and returns its name or an empty string
app.get('/login', function (req, res) {
if (typeof (req.session.user_id) == "number") {
res.json(users[req.session.user_id].name);
return;
}
res.json("");
});
// Check if the user exists and if the password is correct
app.post('/login', function (req, res) {
var post = req.body;
var user = findUser(post.name);
if( !!user && post.password == user.password)
{
req.session.user_id = user.id;
res.json(true);
return;
}
res.json(false);
});
My user is already registered and the login request returns successfully. But after logged in, my GET request to getUserName returns an empty string. What I don't get is where is the session.user_id set? Doesn't the client has to now it?
I have already seen couple of solutions by using passport, etc but I would like to understand the basic of the session/user id handling.
Thanks a lot for your help
Here:
var post = req.body; // the request body with username & password.
var user = findUser(post.name); // you are extracting the username
if( !!user && post.password == user.password)
//---------------------------^^^^^^^^^^^^^-----this isn't available in it.
In your var post you have all the posted request body, which has name & password.
In your var user you are extracting the name out of posted values.
Now in your if condition i don't think user.password is available.
Either make sure you would return the object from findUser(post.name) or change it to: post.password != ""

Categories

Resources