expressjs - 使用Node如何将错误发送回Backbone?

时间:2014-06-11 06:03:09

标签: node.js backbone.js express

当我没有得到用户名或密码时,我无法将错误发送回骨干网。成功后我正在获得成功消息。任何一个更正我的节点代码pelease?

这是我的节点代码:

    var 
    http    = require('http'),
    express = require('express'),
    path    = require('path'),
    jade    = require('jade'),
    stylus  = require('stylus'),
    nib     = require('nib'),
    fs      = require('fs'),
    app     = express();

    function compile(str, path) {
      return stylus(str)
        .set('filename', path)
        .set('compress', true)
        .use(nib());
    }

    app.set('view engine', 'jade');
    app.set('views', __dirname);
    app.use(express.json());
    app.use(express.urlencoded());
    app.use(app.router);

    app.use(stylus.middleware({
        src: __dirname + '/ui',
        compile:compile,
        compress: true
    }));

    app.use(express.static(__dirname +'/ui'));

    app.all('/', function(req, res, next){

        var html;

        fs.readFile('ui/index.html', function(err, data){
            if(err) throw err;
            var fn = jade.compile(data);
            html = fn({name:'Oleg'});

            res.send(html);
        });

    });

    app.post('/home', function(req, res, error){
        var name = req.body.userName,
            password = req.body.password;

if(!name){
return "failed" //not working
}

if(!password){
return "failed" //not working
}

        var successObj = {
            "userName" : name,
            "password" : password
        }

           return res.send(successObj); //i am getting proper out put in backbone. how to send error in case name or password not there?
    });


    http.createServer(app).listen(3000, function(){
        console.log("i am listning to 3000!");
    });

1 个答案:

答案 0 :(得分:0)

您可以在REST服务中使用HTTP状态代码来指定错误。以下是状态代码列表http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

在你的情况下,可以使用401。

res.send方法可以接受状态代码作为第一个参数: http://expressjs.com/4x/api.html#res.send

您也可以使用res.json并指定错误的详细信息 http://expressjs.com/4x/api.html#res.json

例如:res.json(401,{错误:'错误的密码'})