如何在查询字符串中发送 javascript 对象?
How do I send a javascript object in a querystring?
我想在查询字符串中发送这个 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 Router 接收请求,随后在 MongoDB 查询中使用参数:
const express = require('express');
const router = new express.Router();
router.get('/endpoint', (req, res) => {
console.log(req.query.searchParams);
...
});
目前,服务器将 req.query.searchParams
显示为字符串
[object Object]
这里有几个问题:
key
和 params[key]
应该是 url 编码的,您可以为此使用 encodeURIComponent(...)
(这是一个标准函数)
- 由于
params[key]
在两种情况下(searchParam,sortParam)是一个对象,所以字符串表示将是[Object object]。而是尝试:return encodeURIComponent(key) + '=' + encodeURIComponent(JSON.stringify(params[key]))
- 在服务器端,您可能需要 运行
JSON.parse(req.query.searchParams)
才能取回您的对象
我想在查询字符串中发送这个 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 Router 接收请求,随后在 MongoDB 查询中使用参数:
const express = require('express');
const router = new express.Router();
router.get('/endpoint', (req, res) => {
console.log(req.query.searchParams);
...
});
目前,服务器将 req.query.searchParams
显示为字符串
[object Object]
这里有几个问题:
key
和params[key]
应该是 url 编码的,您可以为此使用encodeURIComponent(...)
(这是一个标准函数)- 由于
params[key]
在两种情况下(searchParam,sortParam)是一个对象,所以字符串表示将是[Object object]。而是尝试:return encodeURIComponent(key) + '=' + encodeURIComponent(JSON.stringify(params[key]))
- 在服务器端,您可能需要 运行
JSON.parse(req.query.searchParams)
才能取回您的对象