Sending strings via ajax to Node.js server running express.js don't work properly

409 Views Asked by At

I'm trying to send strings from my site to my Node.js server, but when they are received, for some reasons some characters are lost.

// Client:
microAjax("/foo?test="+encodeURI("this is ++ a test"), function callback(){});

// Server:
app.get('/foo',function(req,res){
    console.log(req.param("test"));
});

Here, both "+" characters appear missing on the server.

1

There are 1 best solutions below

0
On

try encodeURIComponent instead of encodeURI. That will give you %2B for the plus signs which should work.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI

Note that encodeURI by itself cannot form proper HTTP GET and POST requests, such as for XMLHTTPRequests, because "&", "+", and "=" are not encoded, which are treated as special characters in GET and POST requests. encodeURIComponent, however, does encode these characters. These behaviors are most likely not consistent across browsers.