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]