Query string parsing is truncated by an apostrophe in Node.js
I'm building a server in Node.js that receives data from Javascript on a website. The data is being sent using jQuery's getJSON method, like so:
$.getJSON(
url,
{
id: track.id,
artist: track.artist,
title: track.title,
album: track.album,
filename: track.filename,
user: track.user,
userId: track.userId,
room: track.room,
timestamp: track.timestamp
}
);
I'm then trying to get at the data using Node's url module like this:
var urlObj = url.parse(request.url, true);
var jsonCallback = urlObj.query["callback"];
This works fine most of the time, but it fails when one of the parameters contains an apostrophe. It looks like it's stopping parsing the query string at the apostrophe. Here's what console.log prints for two different query objects:
{ callback: 'jQuery15105242477038409561_1304925579219',
id: '6c91c74db064c93f1f020000',
artist: 'Radiohead',
title: 'Everything In Its Right Place',
album: 'Kid A',
filename: '01 Everything In Its Right Place.m4a',
user: 'Cowrelish',
userId: '82a89b4df7a9120305000000',
room: 'qwantz',
timestamp: '1304924972555',
_: '1304925611362' }
{ callback: 'jQuery15105242477038409561_1304925579221',
id: '798cc74dfcce4337f7010000',
artist: 'Toy Dolls',
tit开发者_如何学Cle: 'The Final Countdown',
album: 'HOLY SHIT!!! IT' }
The album for the second one is "HOLY SHIT!! IT'S THE FINAL COUNTDOWN!", as you can see it's been truncated at the apostrophe.
I've tried escaping the apostrophe in the client code, but all I get then is "album: 'HOLY SHIT!!! IT\\'". It's escaping the slash, but not the apostrophe.
Is this a bug or a feature? Should I be escaping apostrophes in a different way on the client, or looking to fix a bug in Node.js?
You shouldn't have to escape on the jquery side, and it doesn't appear to be a node bug (at least with latest release).
I tried to duplicate your problem and wasn't able to using node 0.4.7.
I did this:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/', {test:"it's a test"});
});
</script>
with node code that just did this on the incoming request:
console.log(require('url').parse(req.url, true));
which gave me:
{ test: 'it\'s a test' }
So, doesn't seem to be a general problem with either jQuery or node.
Have you looked at the full url before it is parsed? You should be able to just copy and paste that into the node interactive shell and do something like this to test:
require('url').parse('http://www.example.org/?q=it\'s working', true);
Anything between the browser and the web server that might be touching the url?
精彩评论