Cmag
Cmag

Reputation: 15750

JavaScript JSON object not parsing correctly

Folks, I keep beating my head against this problem. In essence, I have a form which submits a string value to search through DynamoDB RangeKey.

If the form contains "NEW Y" the function seems to break. If I stick "NEW%20Y", things work as expected. I see the following error if the space is used:

error: socket hang up

Somewhere in this code it must not be passing spaces correctly. What is baffling that 'some' spaces work, some dont.

exports.nameSearch = function (req, res) {
  getJSON = function(options, onResult){
    //console.log("rest::getJSON");
    var prot = options.port == 8443 ? https : http;
    var req = prot.request(options, function(res)
    {
        var output = '';
        console.log(options.host + ':' + res.statusCode);
        res.setEncoding('utf8');

        res.on('data', function (chunk) {
            output += chunk;
        });

        res.on('end', function() {
            var obj = JSON.parse(output);
            onResult(res.statusCode, obj);
        });
    });
    req.on('error', function(err) {
        res.send('error: ' + err.message);
    });
    req.end();
};

if (!req.session.username) {
    res.redirect('/login');
} else {
    options = {
        host: 'api.me.com',
        port: 8443,
        path: '/usr/name/'+req.body.name,
        method: 'GET',
        rejectUnauthorized: false,
        requestCert: true,
        agent: false,
        headers: {
            'Content-Type': 'application/json'
            }
    };//options

    getJSON(options,function(statusCode, result) {
        console.log("onResult: (" + statusCode + ")" + JSON.stringify(result));

        // Check if we found anything
        status = JSON.stringify(result.Count)
        if (status == 'undefined') {
            console.log ('Nothing Found by the name,', req.body.name)
            var count = '0'
            res.render('user/nameSearch', { title: 'title', count: count, req: req });
        } else {
            results = JSON.stringify(result)
            console.log ("results 1 ok , ", results)
            results = JSON.parse(results)
            console.log ("results 2 ok , ", results)
            res.render('base/nameSearch', { title: 'title', baseResults: results, req: req })
        }

    });// JSON
} // else

};

Upvotes: 0

Views: 566

Answers (1)

djechlin
djechlin

Reputation: 60748

If the form contains "NEW Y" the function seems to break. If I stick "NEW%20Y", things work as expected.

That means somewhere you are url decoding your input, so you need to figure out which middleware does this. Possibly the built-in unescape function. But as it stands your question is too general for me to narrow down where urlencoded input is expected.

Upvotes: 1

Related Questions