سؤال

I am trying to read the parameters value from req.params but in a different way (I am trying to make an API in RESTIFY).

First I read the keys that are available in req.params, like;

var requestData = Object.keys(request.params);

And than I loop through each key and try to fetch its value. below is the code;

for(i = 1; i < requestData.length; i++) {
             keyValue = requestData[i];
             console.log(request.params.keyValue);
        }

But the output shows me UNDEFINED.

Reason: I am trying to read the parameters this way because, then, I do not need to know the name of each parameter.

Below is the complete code:

var restify = require('restify');
var assert = require('assert');

var server = restify.createServer();
var client = restify.createStringClient({
    url: 'http://example.com'
});

function onRequest(request, response, next)
{
    console.log(request.params);
        var requestData = Object.keys(request.params);
        var customJsonString = '';
        var keyValue = '';

        for(i = 1; i < requestData.length; i++) {
             keyValue = requestData[i];
             console.log(request.params.keyValue);
             customJsonString += "" + requestData[i] + " : " + requestData[i] + ", ";
        }

        console.log(customJsonString);
}

function start()
{
    server.use(restify.fullResponse()).use(restify.bodyParser());
    server.get(/^\/(.*)/, onRequest);
    server.post(/^\/(.*)/, onRequest);
    server.listen(8888);

    console.log("Server has started.");
}

exports.start = start;

I will really appreciate any help regarding this issue.

هل كانت مفيدة؟

المحلول

Try this instead:

console.log(request.params[keyValue]);

request.params.keyValue means Give me the value of the property keyValue, whereas the code above means Give me the value of the property whose name is stored in the variable keyValue.

Also, are you sure you want to start with i = 1? Javascript-arrays are 0-based, so I think you want i = 0 instead.

نصائح أخرى

It could help if you can give us the URL you are testing right now as well as the console output your get.

However, please note that arrays in Javascript have 0 based index and your loop should look like this:

for(var i = 0; i < requestData.length; i++) {
}

To loop through the properties of an object, you should probably use for..in anyway:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

I don't know if that will solve your problem but it's a start.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top