Search code examples
javascriptnode.jssails.js

Sails.JS how to get a HTTP GET method in the controller to work properly with URL parameters


I'm having a controller in Sails.JS which needs to take URL parameters like the following: localhost:1337/api/test/[value1]/[value2]

How can I tell the controller to do exactly this? I've already tried to include a :value! or something like that localhost:1337/api/test/:value1 as suggested https://sailsjs.com/documentation/reference/request-req/req-params but the controller doesn't recognice the query to this localhost:1337/api/test/MyValue with req.param("value1").

Any suggestions here?

The routes.js file contains the following:

'get api/test/:value1': 'TestController.test',

and the controller method looks like this:

test: function(req, res) {
        sails.log("req.params = " + JSON.stringify(req.params.all()));
        if (req.method == "GET"){
            var value1 = req.param("value1");
            Test.findOne({"value1": value1).exec(function (err, value1){
                if(err) {
                    sails.log(err);
                    return res.serverError(err);
                }
                if(!value1){
                    //Some error
                }
                return res.ok(value1);
            });
        } else {
            var wrongHttpMethod = req.__('Wrong HTTP method');
            return res.notFound(wrongHttpMethod);
        }
    }

So the basic question is: How do I get a HTTP GET method to run with URL (or query) parameters?


Solution

  • Resolved by itself. Didn't find the error but it works.