Nipun
Nipun

Reputation: 4319

url in expressjs not giving the right query string

I am using expressjs in nodejs for creating my api. Now when I am sending a string as "Wed Jul 29 2015 17:34:22 GMT+0830" in the get request in the querystring and parsing it as url.parse(uri, true).query it gives me a string as "Wed Jul 29 2015 17:34:22 GMT 0830" without the '+'. How can I get the + in the string

Updating with the code

getEventTimeFromurl: function(ctx){

        var decodeURI = decodeURIComponent(ctx.req.url);
        var eventTime = undefined;
        const strEventTime = "eventTime=";

        var eventTimeindex = decodeURI.search(strEventTime);
        if (eventTimeindex == -1)
            throwError.badRequest(ctx, 101, 'Invalid event time');

        var aftereventtime = decodeURI.substring(eventTimeindex + strEventTime.length);
        var endIndex = aftereventtime.indexOf('&');
        if (endIndex == -1)
            eventTime = aftereventtime;
        else
            eventTime = aftereventtime.substring(0, endIndex);

        return eventTime;

    }

Here eventTime= is in the query string which have '+' sign like 'Mon Aug 03 2015 13:27:24 GMT+0930'.

Upvotes: 1

Views: 854

Answers (2)

robertklep
robertklep

Reputation: 203519

Instead of having url.parse() parse the query string, you can first replace any + characters in it by their URL-encoded version (%2b) and then parse the query string manually:

var qs = require('querystring');

var querystring = url.parse(uri).query.replace(/\+/g, '%2b');
var query       = qs.parse(querystring);

Although this assumes that all + characters in the query string need to be kept. If that's not acceptable, you can probably modify the regular expression to match only specific cases (like in timezone notations).

EDIT: combined with Express, it would look something like this:

app.get('/', function(req, res) {
  var querystring = url.parse(req.url).query.replace(/\+/g, '%2b');
  var query       = qs.parse(querystring);
  ...
});

Upvotes: 0

Hiren S.
Hiren S.

Reputation: 2832

You can encode string to URI format.

var dateString = "Wed Jul 29 2015 17:34:22 GMT+0830";
var encodedString = encodeURIComponent(dateString);

use encodedString to pass it in the query string.

Upvotes: 1

Related Questions