Extra quotes in req.query object - javascript

I have a problem with extra quotes in req.query object. I'm using Angular.JS(1.5.8) with NodeJS(6.2.0).
So what i mean:
On client side I have simple REST api
.factory('Users', function ($resource) {
var Users = $resource("api/users/" + ":_id", { _id: "#_id" }, {update: {method: 'PUT'}, query:{ method: "GET", isArray: false }});
return Users;
})
And use it like this
return Users.query({a: 'some text', b: 10}}).$promise.then(function(results){
return results.users;
});
And all works fine, on server I'm get as results console.log('Query parsing - ', req.query); - Query - { a: 'some text', b: '10' }
But when I'm trying to send nested object:
Users.query({a: 'some text', b: {first: 10, second: 20}})
On server I have results with extra quotes and object not valid: Query - { a: 'some text', b: '{"first":10,"second":20}' }.
As result I cannot use it for mongoose queries. When I waited for {$text:{"$search":"admin"}} I'm recived {$text:'{"$search":"admin"}'}.
Can someone faced this problem before. Thanks for the help

JSON/Object to QueryString and back conversion has many many issues. Nesting, Arrays, "null", boolean values etc. You just encountered one.
Simplest solution is to JSON.stringify() objects as query string value:
url = 'www.example.com' + '/resource' + '?json=' + JSON.stringify(dataObject);
Browsers will automatically URL encode the JSON string. On other clients you may have to do it manually.
You can parse it back on server. For example this expressjs middleware:
app.use(function(req, res, next){
if(req.query.json){
try {
req.query.json = JSON.parse(req.query.json);
next();
}catch(err){
next(err);
}
}
});

Related

Axios sends an array of strings instead of an array of objects

Axios sends an array of strings instead of an array of objects. I have an array of objects that contains data about the event. I'm trying to send a request to the server via axios, but I get a array of strings insteenter image description heread of objects at the output
let data = {
title: 'Game',
subject: 'Some subject',
date: ['01/01/2021','01/01/2021'],
years: ['1970', '1970'],
address: 'None',
ages: [
{
title: 'Men',
weights: [{page: 0, title: '60'}]
}
]
};
api.Create({
params: data
}).then(function (response) {
console.log(response.data);
})
.catch(function (err) {
console.log(err);
});
api response
try to:
console.log(JSON.parse(response.data))
What you get back from the server is string. you need to parse it.
When you send data to and from a server, it is sent as a 'serialized' string, usually JSON format
That's how server responses work
It turned out to be an incorrect request. I used GET to pass the object, instead of POST, so it converts it to a string. I want to notice that there is an evil community on this site.

JavaScript: TypeError: Converting circular structure to JSON when posting to discord

I have the array sessionCookies which looks like this:
[ { name: 'cookie_name',
value: 'I WANT THIS VALUE ONLY',
domain: 'cookie domain',
path: '/',
expires: -1,
size: 43,
httpOnly: true,
secure: true,
session: true } ]
I am then creating and using the function findCookie to get the value "I WANT THIS VALUE ONLY" seen in the array above using this code:
function findCookie(name) {
for (let i in sessionCookies) {
if (!sessionCookies.hasOwnProperty(i)) {
continue;
}
if (sessionCookies[i].name === name) {
return (sessionCookies[i].value);
}
}
}
const mycookievalue = findCookie('cookie_name');
console.log(mycookievalue); then obviously prints out: I WANT THIS VALUE ONLY
I am then trying to send that variable mycookievalue to discord using the webhook-discord library however it is throwing me the error: TypeError: Converting circular structure to JSON. This is the code I use to send the webhook:
const webhook = require("webhook-discord")
const Hook = new webhook.Webhook("my webhook link")
const msg = new webhook.MessageBuilder()
.setName("Cookie")
.setColor("#2fed5c")
.setText("Got the cookie")
.addField("My Cookie", mycookievalue)
.setTime();
Hook.send(msg);
That sending to discord is throwing me the error as stated above which I do not know how to get rid of since JSON.stringify will not work either. Any help is appreciated!

How to emit object using socket.io?

I have a code like, I have a problem with sending response.
socket.on('findUserMessages', (userName) => {
io.sockets.connected[socket.id].emit('Checking-message', {
type: 'ss',
text: bot,
user: 'bot'
});
var dupa = db.chat.find({ user: userName }, function(err, docs) {
userName = userName
if (err) throw err;
console.log('load old messages', docs)
})
io.emit('private message', dupa);
})
My node console output is like
[ { _id: 5888bdd6cef7952e38821f35,
text: 'O rajciu rajciu',
user: 'Adam',
time: 2017-01-25T15:01:42.733Z }]
I know that output is not a JSON string, how to solve that? I was trying to use .toArray() but without succes.
That might be silly question but I am stuck with it for a long time.
Convert to json your result before emitting it. Try to emit JSON.stringify(dupa).
EDIT
Your output is actually JSON already (JSON array), so if you want to get only JSON string on client side, convert your output to string there (JSON.strigify(result) on client side on receiving the emit event).

Expressjs How to properly pass an array from the client and utilize it?

I have an object that look like this:
editinvite: {
_id: '',
title: '',
codes_list: []
}
The problem is that I can't access codes_list in my NodeJS app. It shows as 'undefined' (other non-array variables work fine though)
router.post('/inviteEdit', function (req, res) {
...
console.log(req.body.codes_list);
// Output:
undefined
Note that I'm trying to use codes_list as it is, I mean I want to pass it directly to my update parameters:
var update = {
title: req.body.title,
codes_list: req.body.codes_list,
};
(extra info) Output of console.log(req.body):
{ _id: '565981a16a75a7522afdcc8b',
title: 'as',
'codes_list[0][code]': '0EHC',
'codes_list[0][_id]': '565981a16a75a7522afdcc8c',
'codes_list[0][used]': 'false',
'codes_list[1][code]': 'VDQ2',
'codes_list[1][_id]': '565981a16a75a7522afdcc8d',
'codes_list[1][used]': 'false' }
(extra info) editinvite object before sending, looks like this on FF debugger:
(extra info) My ajax call:
$.ajax({
type: 'post',
url: this.server + '/inviteEdit',
dataType: 'json',
data: this.editinvite,
crossDomain: true,
success: function (data, status, jqXHR) {
...
(extra info) I'm using these parameters in node app
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
Quoting from body-parser documentation:
bodyParser.urlencoded(options) returns middleware that only parses
urlencoded bodies. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.
A new body object containing the parsed data is populated on the
request object after the middleware (i.e. req.body). This object will
contain key-value pairs, where the value can be a string or array
(when extended is false), or any type (when extended is true).
So basically if you just want string or array to be parsed you can set extended to false, for other types (like in your case array of objects) you need to set it to true.

Merging req.params and req.url in express

First of all, I have the following route:
route: '/list/:param1'
Im sending the following request to the server:
url: '/list/someParam?param2=foo&param3=bar
After that, express is giving to me two important objects that i need, the req.url and the req.params.
I want to get an object that merges both url and params. Im using the following code:
module.exports = function (req, res, next) {
var url = require('url');
var queryObject = url.parse(req.url, true).query;
console.log(queryObject);
console.log(req.params);
console.log(req.params.length);
}
So it logs something like:
{ param2: 'foo', param3: 'bar' }
[ param1: 'someParam' ]
0
Now, assuming that I dont know the name of the params, I need to have an object with the information from both req.url and req.params. Here are my questions:
1) How can I do to get something like:
{ param1: 'someParam', param2: 'foo', param3: 'bar' }
2) Why is req.params logging something like an array? And if it is an array, why is it returning me 0 as its length?
Thanks in advance.
Use req.query instead of parsing the URL again.
I'm guessing Express has a custom toString implementation for that particular object.
You can also look up both in order of importance using req.param(name)

Categories