1

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]

5
  • what is console.log(JSON.stringify(req.query.searchParams)); showing? Commented Dec 29, 2016 at 23:05
  • 1
    Also: don't format parameters like this. They need to be url-encoded. If you happen to use jquery, use its jquery.params method which does the heavy lifting for you. Commented Dec 29, 2016 at 23:08
  • You need to convert your object to JSON. It Is using the native object toString method. Commented Dec 29, 2016 at 23:08
  • console.log(JSON.stringify(req.query.searchParams)); shows "[object Object]" Commented Dec 29, 2016 at 23:13
  • I am not using jQuery - what should I use to urlencode? Commented Dec 29, 2016 at 23:14

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.