JoeTidee
JoeTidee

Reputation: 26044

How do I send a javascript object in a querystring?

I want to send this javascript object in a query string so that I can use it as an object when received by the server. Currently, I am using 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();

Where formatParams function is as follows:

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

On the server I am receiving the request via an Express Router, where the parameters are subsequently used in a MongoDB query:

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

Currently, the server is showing req.query.searchParams as a string

[object Object]

Upvotes: 1

Views: 3946

Answers (1)

Jochen Bedersdorfer
Jochen Bedersdorfer

Reputation: 4122

There are a few issues here:

  1. key and params[key] should be url-encoded, you can use encodeURIComponent(...) for this (it's a standard function)
  2. Since params[key] is an object in two cases (searchParam, sortParam), the string presentation will be [Object object]. Instead try: return encodeURIComponent(key) + '=' + encodeURIComponent(JSON.stringify(params[key]))
  3. On the server-side, you probably need to run JSON.parse(req.query.searchParams) to get your object back

Upvotes: 2

Related Questions