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

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

Related

Updating field value in a MongoDB document is turning string into object

I am currently making a project using React TypeScript, MongoDB, and Express.js. I am trying to update the field value in my MongoDB document, and it is supposed to be a string, but instead it is automatically turning it into an object. Has anyone had that problem before? If so, how did you fix it?
How it's supposed to be:
character_name: "string"
How it's updating:
character_name: {
"string": ""
}
I've even logged it in the console to show me the type of data, and it's saying it's a string, so I don't know what it could be doing?
The backend routes:
routes.put("/change-name", async (req, res) => {
const name = req.body as string;
try {
const client = await getClient();
const result = await client.db().collection<Account>('accounts').updateOne({ username: "AndrewDamas" }, {$set: {character_name: name}});
if (result.modifiedCount === 0) {
res.status(404).json({ message: "Not Found" });
} else {
res.json(name);
}
} catch (err) {
console.error("FAIL", err);
res.status(500).json({ message: "Internal Server Error" });
}
});
The service code on the frontend side:
export function changeName(name: string){
return axios.put(`${baseUrl}/change-name`, name)
.then(res => res.data);
}
And how I used it in my code:
function saveData(){
console.log(ourCharacterName);
changeName(ourCharacterName);
}
Any help would be greatly appreciated! Thanks.
Put request. When sending data as body, it's going to arrive as json in your server . So you can either deconstruct it or use dot notation in your route method.
return axios.put(`${baseUrl}/change-name`, {name:name})
Deconstruct the variable from the body
const {name} = req.body;
Update the document
... {$set: {character_name: name}}
Problem
Every time you use as in TypeScript it means that something is wrong.
const name = req.body as string;
Your body isn't really a string, your body is the object:
{
"string": ""
}
Solution
const { string: name } = req.body;

Getting bad request error when updating a number in MongoDB

I was trying to update a single element(which is a number) that is stored in mongodb.
here is the request I sent to the DB:
const handleDelivered = (num) =>{
const total = service.quantity;
const final = parseInt(total) + num;
console.log(total,final);
const url = `http://localhost:5000/services/${idOfService}`;
fetch(url,{
method :'PUT',
headers :{
'content-type': 'application/json',
},
body : JSON.stringify(final)
})
.then(res => res.json())
.then(product =>{
console.log(product);
})
}
The data stored inside MongoDB is an object of the array. to execute the operation I tried to build an API with express.
here is the code for the API
app.put('/services/:id', async(req,res)=>{
const id = req.params.id;
const filter = {_id : ObjectId(id)};
const options = { upsert: true };
const updatedData = req.body;
const updateDoc = {
$set: {
quantity : updatedData.quantity,
},
};
const result = await serviceCollection.updateOne(filter, updateDoc, options);
res.send(result);
});
Whenever I click on the button to update it shows an error saying:
PUT(link)400 (bad request)
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
This should work for you:
In you request body do this:
body : JSON.stringify({quantity: final})
Instead, send an object as a string whit:
res.send(result);
Send as a JSON like this:
res.status(200).json(result);
And to your client to catch better the error that your service throw add the closure catch to the fetch.

Javascript Object Undefined - Jquery + Node JS

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

TypeError: data.filter is not a function

I am trying to filter an array of JSON objects, which I get from an API call on my proxy. I am using a Node.js web framework Express to make the API call.
API returns the following:
{
data: [
{
type: "aaa",
name: "Cycle",
id: "c949up9c",
category: ["A","B"]
},
{
type: "bbb",
name: "mobile",
id: "c2rt4Jtu",
category: ["C","D"]
},
...
]
}
server.js
function sortDataByID(data) {
return data.filter(function(item) {
return item.id == 'c949up9c';
});
}
app.get('/products', (req, res) => {
const options = {
url: BASE_URL + '/products',
headers: {
'Authorization': 'hgjhgjh',
'Accept': 'application/json'
}
}
request.get(options).pipe(sortDataByID(res));
});
I keep getting the following error message.
TypeError: data.filter is not a function
What is the obvious mistake here? Anyone?
I think your mistake is to think than res is the data than you expect.
But if you take a look inside res you should find the data.
so you must get datafrom the res and use it.
For example:
const data = res.data;
request.get(options).pipe(sortDataByID(data))
Have a nice day !
I've personally never seen piping to a function. I don't think that should work. In any case:
You can use a callback instead of piping. Try this:
app.get('/products', (req, res) => {
const options = {
url: BASE_URL + '/products',
json: true, //little convenience flag to set the requisite JSON headers
headers: {
'Authorization': 'hgjhgjh',
'Accept': 'application/json'
}
}
request.get(options, sortDataByID);
});
function sortDataByID(err, response, data){ //the callback must take 3 parameters
if(err){
return res.json(err); //make sure there was no error
}
if(response.statusCode < 200 || response.statusCode > 299) { //Check for a non-error status code
return res.status(400).json(err)
}
let dataToReturn = data.data.filter(function(item) { //data.data because you need to access the data property on the response body.
return item.id == 'c949up9c';
}
res.json(dataToReturn);
}
I received TypeError: data.filter is not a function while doing Unit testing.
I was passing an object not an array in the result.
gateIn$: of({}),
instead of
gateIn$: of([]),
gateIn$.pipe(takeUntil(this.destroy$)).subscribe(bookings => (this.dataSource.data = bookings));
once you see the error it is pretty obvious, the hard bit is spotting it in the first place.

React-native async fetch returns null

I am trying to put fetch functions into a separated file, so I can organise these API fetch easily. However, when I try to fetch and return the data, it gives me null or an unexpected json object. Here is part of my src:
//api.js
export async function LoginAPI(username, password) {
const url = baseURL + "/login/";
var params = {username: username, password: md5.hex_md5(password)};
let response = await fetch(url, {
method: 'POST',
headers: {'Accept': 'application/json','Content-Type': 'application/x-www-form-urlencoded'},
body: JSON.stringify(params)
});
return await fetch(url, {
method: 'POST',
headers: header,
body: JSON.stringify(params)
})
.then((res) => res.text())
.then((text) => text.length ? JSON.parse(text) : {})
.catch((error) => {
throw error;
});
};
Here is the another file.
//index.js
var Login = React.createClass({
onPress_login: function() {
var value = this.refs.form.getValue();
if (value) {
result = LoginAPI(value.username, value.password);
console.log(result);
} else {
this.AlertDialog.openDialog();
}
},
render() {
return (
(...)
<Button onPress={this.onPress_login}>
<Text>Login</Text>
</Button>
The fetch is working, it is communicating with the server. However, the console log returns me this at the first place
Promise _45: 0_54: null _65: null _81: 1 __proto__: Object
I am assuming that the result log in the console at the first place is not the await result (the actual response from server, but an object of fetch response). I tried to search out methods online but I can't find any post/blog/article saying how to do fetch as a function call.
Is there any way to do like swift, LoginAPI(username, password, callback: {...}) please?
The problem is that you're are making an async function and not waiting for the response, the you see that kind of console log.
Try this:
result = await LoginAPI(value.username, value.password);
Let me know if this was your problem.

Categories

Resources