What is the best way to incorporate a JavaScript object into a query string for transmission?

I am currently working on sending a JavaScript object in a query string to use it as an object when received by the server. My approach involves making an xhr request:

        const xhr = new XMLHttpRequest();
        var params = {
            searchParams: {name: 'Joe'},
            sortParam: {name: -1},
            skip: 0,
            limit: 50
        };
        xhr.open('get', '/api/endpoint' + formatParams(params));
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr.responseType = 'json';
        xhr.addEventListener('load', () => {
            if (xhr.status === 200) {
                ...
            }
            else{
                ...
            }
        });
        xhr.send();

To achieve this, I have defined a function called formatParams:

const formatParams = ( params ) => {
    return "?" + Object
            .keys(params)
            .map(function(key){
                return key+"="+params[key]
            })
            .join("&")
};

Upon receiving the request on the server via an Express Router, I proceed to utilize the parameters in a MongoDB query:

const express = require('express');
const router = new express.Router();
router.get('/endpoint', (req, res) => {
    console.log(req.query.searchParams);
    ...
});

However, when checking the server response for req.query.searchParams, it displays as:

[object Object]

Answer №1

There are several issues that need to be addressed:

  1. The variables key and params[key] should be properly url-encoded using the standard function encodeURIComponent(...)
  2. When params[key] is an object in certain cases (such as searchParam or sortParam), displaying it as [Object object] will not be helpful. Instead, encode it like this:
    return encodeURIComponent(key) + '=' + encodeURIComponent(JSON.stringify(params[key]))
  3. On the server-side, ensure that you use
    JSON.parse(req.query.searchParams)
    to receive your object correctly

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Verify whether a dependency is being passed into an Angular component

As mentioned in a discussion about IE caching issues, Internet Explorer tends to cache things when using ajax with AngularJS, causing potential problems. You can find a helpful solution to this problem here. Given that we have multiple angular apps on our ...

Which specific file name patterns does npm publish consistently exclude?

When using the npm publish command, the documentation mentions that certain files will not be included in the package unless explicitly added to the "files" list in package.json or un-ignored with a specific rule. What exactly are these "certain patterns"? ...

What is the best way to pinpoint the initial and final elements in a row of variable entries within a grid?

These are the tools currently in use: Vuejs Jquery Packery with masonry layout The project involves creating a page that pulls content from JSON and fills the homepage with posts, products, and pages in a single loop. Each object in the loop is arranged ...

Iterate over an array in JavaScript and include the elements as parameters in an SQL query

Can I set an SQL string to a variable in JavaScript and populate part of it by looping through an array? Here is the initial SQL: var tag = ["fun", "beach", "sun"]; var sql = "SELECT * FROM myTable " +"WHERE id > 5" //... // L ...

Utilizing the Express.js hbs module to easily incorporate partials from .hbs files

Currently, I am utilizing the handlebars.js hbs wrapper with express.js. My templates are functioning correctly, but now I have a requirement to incorporate partials into my views. My desired approach is as follows: hbs.registerPartial('headPartial& ...

What's the best way to separate and save data in a variable in JavaScript?

I need to split this code and store it in three different variables, like a=GD11, b=GDP7 and c=GD11, but I am having trouble because breaking at "s" results in "GDP7xGD11". Can someone please help me figure out how to break it into three separate variable ...

javascript ways of passing a value from an event function to an outer function

Could use a hand with this - looking to pass a variable from an input event function to an outer function. function takeInputText() { var input = document.getElementById('inputText') var newText; input.onkeyup = function(e) { ...

Align the inline text at the center as if it were an inline-block element

Currently working on a design that appears deceptively simple, yet I'm encountering challenges in centering it while keeping the text aligned to the left. https://i.sstatic.net/qhf6p.png In an attempt to have the background span only the actual text ...

In my chat application, I encountered the error message "Received an expression instead of an assignment or function call - no-unused-expressions"

While working on my React Chat app and trying to access my Firebase, I encountered the error message: "Expected an assignment or function call and instead saw an expression no-unused-expressions" The error seems to be related to the assignment of this.rem ...

karma: Error: Unable to access the 'prototype' property of an undefined object

Whenever I attempt to inject my service, the following error occurs: (function () { describe('Test', function () { var $scope, $state, service,ctrl; beforeEach(function() { module('moduleApp'); ...

What is the best way to incorporate a @types module into a TypeScript file that is not already a module?

Setting the Stage: In the process of shifting a hefty ~3,000 line inline <script> from a web-page to a TypeScript file (PageScripts.ts) to be utilized by the page through <script src="PageScripts.js" defer></script>. This script entails ...

What is the best way to utilize JavaScript variables that are declared on index.html/index.jsp in Vue.js?

Just starting out with Vue.js and I recently finished developing a Vue.js app using the terminal. I then deployed it on a Java web application and noticed that everything works fine when running it as is. However, I now need to pass a csrftoken to my Vu ...

Press a single button to toggle between displaying and hiding the table

$(document).ready(function() { $("#t1").hide(); // hide table by default $('#sp1').on('click', function() { $("#t1").show(); }); $('#close').on('click', function() { $("#t1").hide(); }); }); <li ...

Tips on using the map and filter methods to narrow down a nested array based on specific object

I am struggling to filter JSON data based on a specific date using Array.Filter and Map. The code I have tried below is not yielding the desired results. Can someone please provide guidance on how to effectively filter JSON data based on a particular date ...

The process of obtaining and sending a token from an HTML page while submitting a form request to a Laravel 5 application involves a few key steps

My application consists of the client side being written in HTML and Angularjs, while the server-side is using Laravel 5. Every time I submit my form, I send the models using $http to a route in my Laravel 5 app, but I continuously encounter the error: pr ...

Compile the sources of an npm dependency using Brunch

Recently, I've been facing an issue while trying to develop my web application using Brunch. The problem arises from a specific npm package called animated-vue, which consists of sources programmed in ES2016. After adding this package as a dependency ...

Dealing with 401 Errors: Navigating Redirects using Vue.js and

Currently, I am utilizing Vue.js along with axios in an attempt to create a generic API object as shown below: import router from './router' import auth from './auth' const axios = require('axios') export const API = axios.c ...

the language of regular expressions expressed in strings

As a beginner in Javascript and regular expressions, I found myself stuck on how to create a route that matches all URLs starting with /user/.... Initially, I thought of using app.get(/user/, function(req, res){ /*stuff*/}); However, curiosity led me to ...

JavaScript provides two different methods for iterating through arrays: `Object.keys(myarray).forEach` and `myarray.forEach((obj)

Is there a different method to iterate through my array of objects? The engine version on the application I'm using seems to be outdated and doesn't support myArray.forEach((obj) => {, but it works when dealing with single object arrays. Try u ...

How can Vue FullCalendar be configured dynamically?

I am trying to dynamically change some options in Vue FullCalendar, but the calendar is not applying them. You can check out my example here. The button at the bottom should set the maxTime option from 20:00 to 18:00. Is there a way to refresh the calen ...