Sails Как перенаправить страницу при ошибке bad request / 400? - PullRequest
0 голосов
/ 06 декабря 2018

Это код, который я использую и хочу отобразить новую страницу при появлении 400 ошибок.

module.exports = function badRequest(err,viewOrRedirect) {  
    // Get access to `req` & `res`  
    var req = this.req;  
    var res = this.res;    
    // Serve JSON (with optional JSONP support)  
    function sendJSON(data) {  
        if (!data) {  
            return res.send();  
        } else {  
            if (typeof data !== 'object' || data instanceof Error) {  
                data = {  
                    error: data  
                };  
            }  
            if (req.options.jsonp && !req.isSocket) {  
                return res.jsonp(data);  
            } else return res.json(data);  
        }  
    }  

    // Set status code  
    res.status(400);  
    // Log error to console  
    this.req._sails.log.verbose('Sent 400 ("Bad Request") response');  
    if (err) {  
        this.req._sails.log.verbose(err);  
    }  
    // If the user-agent wants JSON, always respond with JSON  
    if (req.wantsJSON) {  
        return sendJSON(err);  
    }  
    // Make data more readable for view locals  
    var locals;  
    if (!err) {  
        locals = {};  
    } else if (typeof err !== 'object') {  
        locals = {  
            error: err  
        };  
    } else {  
        var readabilify = function(value) {  
            if (sails.util.isArray(value)) {  
                return sails.util.map(value, readabilify);  
            } else if (sails.util.isPlainObject(value)) {  
                return sails.util.inspect(value);  
            } else return value;  
        };  
        locals = {  
            error: readabilify(err)  
        };  
    }  
    // Serve HTML view or redirect to specified URL  
    if (typeof viewOrRedirect === 'string') {  
        if (viewOrRedirect.match(/^(\/|http:\/\/|https:\/\/)/)) {  
            return res.redirect(viewOrRedirect);  
        } else return res.view(viewOrRedirect, locals, function   viewReady(viewErr, html) {  
            if (viewErr) return sendJSON(err);  
            else return res.send(html);  
        });  
    } else return res.view('400', locals, function viewReady(viewErr, html)   {  
        if (viewErr) return sendJSON(err);  
        else return res.send(html);  
    });  
};  

Ответы [ 2 ]

0 голосов
/ 04 мая 2019

Для переадресации на 404 можно просто использовать это:

return res.notFound();

документы

0 голосов
/ 06 декабря 2018

Сделайте перенаправление одним из ваших выходов:

redirect: { responseType: 'redirect' },

Затем сделайте любую проверку, которую вы делаете, и бросьте выход: // Permissions if(!this.req.me) { throw { redirect: '/login' }; }

...