我希望在查询字符串中发送这个javascript对象,以便当服务器接收到它时,我可以将它用作一个对象。目前,我正在使用xhr请求:
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();
其中formatParams函数如下:
const formatParams = ( params ) => {
return "?" + Object
.keys(params)
.map(function(key){
return key+"="+params[key]
})
.join("&")
};
在服务器上,我通过一个Express路由器接收请求,随后在MongoDB查询中使用这些参数:
const express = require('express');
const router = new express.Router();
router.get('/endpoint', (req, res) => {
console.log(req.query.searchParams);
...
});
当前,服务器将req.query.searchParams
显示为字符串。
对象对象
发布于 2016-12-29 15:18:17
这里有几个问题:
key
和params[key]
应该是url编码的,您可以为此使用encodeURIComponent(...)
(这是一个标准函数)params[key]
在两种情况下都是对象(searchParam,sortParam),所以字符串表示将是对象。相反,请尝试:return encodeURIComponent(key) + '=' + encodeURIComponent(JSON.stringify(params[key]))
JSON.parse(req.query.searchParams)
才能使对象返回。https://stackoverflow.com/questions/41388403
复制