Seems that every parameters passed in a http request is a string type.
So, if I want to pass two values that are, for example, boo = true and str = "true" they will be encoded in the same way:
/server/test?boo=true&str=true.
I don't know if there is something that I'm doing wrong, but if it's so, I guess it can be very frustrating to deduce everytime the type of a parameter on the server side as it can cause type misunderstanding on server side.
I found the same issue even in php and in nodejs. The weird thing is that when instead the server returns a json stringified value, it works perfect on javascript and parameters still preserve the original types.
But it seems (as far as I know) that there's no way to pass directly a json stringified uri and then capture it with a json parsing.
My solution, till now, is to pass a value 'data' with json stringified object as value, containing all the parameters I want to get on server. Something like this:
(request to node.js)
$.post('server/test', {data: JSON.stringify({boo:true, str: 'true'})}).then( function (res) {
console.log (res.boo === true); //true
console.log (res.str === 'true'); //true
});
(server side nodejs)
const express = require('express'),
bodyParser = require('body-parser'),
app = express();
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded({extended: true}) );
app.listen(8080);
app.post ('/server/test', async (req, res) => {
let {boo, str} = JSON.parse(req.body.data);
res.send({boo: boo, str: str});
});
(request to php)
$.post('includes/server.php', {
data: JSON.stringify({boo: true, str: 'true'})
}).then( function (res) {
res = JSON.parse(res);
console.log (res.boo === true); //true
console.log (res.str === 'true'); //true
});
(server side php)
$data = json_decode( $_POST["data"] );
$boo = $data->boo; $str = $data->str;
$res = (object) ["boo"=> $boo, "str"=> $str];
echo json_encode($res);
I wonder if someone knows a better (and simpler) solution to solve this issue, or if this is the best to preserve types on parameters.