Overwrite default routes in sailsjs

1

I have a controller called UsersController with the following method:

module.exports = {
    index: function(req, res, next){
        Users.find({}, function(err, users){
            if(err) return next(err);
            if(!users) return next();

            res.json({"data": users});
        });
    },
}

Which gives me a JSON like this:

{
    data: [
        {
            name: "Jhon Doe",
            username: "jhon.doe",
            email: "[email protected]",
            role: 1,
            logged: 0,
            status: 1,
            id: 1,
            createdAt: "2016-10-28T00:42:04.000Z",
            updatedAt: "2016-10-28T00:42:04.000Z"
        }
    ]
}

And in my file config/routes.js

module.exports.routes = {
    'GET /users/GET_ALL': {
        controller: "UsersController",
        action: "index"
    }
}

If I access both routes /users/ and /users/GET_ALL/ I can get the JSON shown above, my question is how can I get it (the JSON ) only through the path /users/GET_ALL/ and that when accessing the other /users/ send me a error 404 or whatever I want to show?

    
asked by Jorius 28.10.2016 в 02:51
source

2 answers

0

Thanks to the answer of Isaac Vega I read a little more about the object req and found that it has a método called path which serves to make the validation I want because it returns the uri which is after the host delivered by giving sails lift to the application:

module.exports = {
    index: function(req, res, next){
        if(req.path == '/users/'){
            res.notFound();
        }else{
            Users.find({}, function(err, users){
                if(err) return next(err);
                if(!users) return next();

                res.json({"data": users});
            });
        }
    },
}

So, if I enter /users/ will return a error 404 , however if I enter /users/GET_ALL/ I get JSON correctly.

    
answered by 29.10.2016 / 20:20
source
1

When you make an HTTP request of any type (GET, POST, PUT, etc ...) you can verify in node.js the headers of the object that you created req (the request of the user, req.headers), and see the type of request that was made. You can control with the module fs that if the request is on the desired route, that the JSON sends, if not, that it sends an error page. For example: a

if(/*direccion incorrecta*/)
    fs.readFile(__dirname + "/403.html", function(e, d) {
        if(e)
            return response.end("403 Forbiden");
        return response.end(d);
    });
else
    //retornar el JSON

When you return response.end (d), you send the client the content of page 403.html that you read, indicating that you can not access that place. I hope it serves you.

    
answered by 29.10.2016 в 19:50