如何在node express中处理多个路由的依赖关系

时间:2017-01-22 01:00:12

标签: javascript node.js express passport.js

我正在尝试在我的node-express-mongod应用程序中实现身份验证。首先,我在我的server.js中创建了一个app.post,但是在使用这个卷曲时难以获得结果:

curl -X POST -H "Content-Type: application/json" -d '{"username": "joe", "password": "passwordtest"}' http://localhost:8080/users

我得到的是: {“message”:“内部服务器错误”}

我当前的server.js看起来像这样:

var express = require('express');
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var mongoose = require('mongoose');
var config = require('./config');
var Item = require('./models/item');
var User = require('./models/user-model');

// Mongoose Connect
var app = express();
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(express.static('public'));

var runServer = function(callback) {
    mongoose.connect(config.DATABASE_URL, function(err) {
        if (err && callback) {
            return callback(err);
        }
        console.log("Connected to mongodb!");
        app.listen(config.PORT, function() {
            console.log('Listening on localhost:' + config.PORT);
            if (callback) {
                callback();
            }
        });
    });
};

if (require.main === module) {
    runServer(function(err) {
        if (err) {
            console.error(err);
        }
    });
};

// Route for passport test
app.post('/users', jsonParser, function(req, res) {
    if (!req.body) {
        return res.status(400).json({
            message: "No request body"
        });
    }

    if (!('username' in req.body)) {
        return res.status(422).json({
            message: 'Missing field: username'
        });
    }

    var username = req.body.username;

    if (typeof username !== 'string') {
        return res.status(422).json({
            message: 'Incorrect field type: username'
        });
    }

    username = username.trim();

    if (username === '') {
        return res.status(422).json({
            message: 'Incorrect field length: username'
        });
    }

    if (!('password' in req.body)) {
        return res.status(422).json({
            message: 'Missing field: password'
        });
    }

    var password = req.body.password;

    if (typeof password !== 'string') {
        return res.status(422).json({
            message: 'Incorrect field type: password'
        });
    }

    password = password.trim();

    if (password === '') {
        return res.status(422).json({
            message: 'Incorrect field length: password'
        });
    }

    var user = new User({
        username: username,
        password: password
    });

    user.save(function(err) {
        if (err) {
            return res.status(500).json({
                message: 'Internal server error'
            });
        }

        return res.status(201).json({});
    });
});

// routes for crud operations
app.get('/items', function(req, res) {
    Item.find(function(err, items) {
        if (err) {
            return res.status(500).json({
                message: 'Internal Server Error'
            });
        }
        res.json(items);
    });
});

app.post('/items', jsonParser, function(req, res) {
    console.log("req:", req.body);

    if (!req.body) {
        return res.sendStatus(400);
    }
    else {
        var favoritesList = req.body;
        res.status(201).json(favoritesList);
    }

    console.log("res:", res.status);
    // console.log("name", name);
    Item.create({
            name: req.body.name,
            wineResults: req.body.wineResults
        },

        function(err, item) {
            if (err) {
                message: err
            }
            else {
                message: "done"
            }
        });
});

app.delete('/items/:name', function(req, res) {


    Item.findOneAndRemove(req.params.name, function(err, items) {
        if (err) {
            return res.status(404).json({
                message: 'Internal Server Error'
            });
        }

        Item.remove({
                name: req.body.name,
                wineResults: req.body.wineResults
            },

            function(err, item) {
                if (err) {
                    message: err
                }
                else {
                    message: "done"
                }
            });
    });
});

app.put('/items/:id', function(req, res) {
  var data = req.body; // data should be validated
  Item.findOneAndUpdate({ name: req.params.id }
    , { $set: { name: data.name }}
    , { returnOriginal: false }
    , function (err, items) {
      if (err) {
        return res.status(500).json({
          message: 'Internal Server Error.'
        });
      }
      return res.json(items);
    }
  );
});


app.use('*', function(req, res) {
    res.status(404).json({
        message: 'Not Found'
    });
});

exports.app = app;
exports.runServer = runServer;

这是user-model.js:

var mongoose = require('mongoose');
var UserSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    }
});

var User = mongoose.model('User', UserSchema);

module.exports = User;

我刚刚学习了身份验证和节点,并且不确定我可以采取哪些其他步骤来解决这个问题。任何帮助表示赞赏。感谢。

0 个答案:

没有答案