使用节点静态的MEAN API无响应

时间:2018-06-25 21:17:05

标签: node.js rest api mean

我正在尝试为使用相同数据库结构(在同一CMS上运行)的多个项目设置API,但是当我尝试获取一些数据时却没有响应。

index.js

var express = require("express");
var cors = require("cors");
var mongoose = require("mongoose");
var bodyParser = require("body-parser");
var methodOverride = require("method-override");
var _ = require("lodash");

var passport = require("passport");
var dbconfig = require("./app/config/database");

// Create the application
var app = express();
var user = require("./app/routes/User");

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(methodOverride('X-HTTP-Method-Override'));

var connections = [];

// Auto CORS 
app.use(cors());

/* Mnual CORS Start 
app.use(function(req, res, next){
    res.header("Access-Controll-Allow-Origin", "*");
    res.header("Access-Controll-Allow-Methods", "GET,PUT,POST,DELETE");
    res.header("Access-Controll-Allow-Headers", "Content-Type");
    next();
});
/* Manual Cords end */

// Passport Middleware
app.use(passport.initialize());
app.use(passport.session());
require("./app/config/passport")(passport);

app.get("/", (req, res) => {
    res.json({ msg: "Nothing here mate" });
});

//------------ THIS IS WORKING ----------------
app.get("/db/:database/navigation", (req, res) => {

    var dbname = req.params.database;
    var conn = connections[dbname];
    var navs = conn.model("navigation", app.models[dbname].navigation);

    // Send json data/error
    if (navs) navs.find({}, (err, data) => res.json(data));
    else res.json({ error: true, msg: "Model not found" });
});
// -------------------------------------------------------

// Setup databases for all projects
_.each(dbconfig.databases, db => {
    var appModels = require("./app/models/index");
    var processed = 0;

    // We will use prefix for all routes /db/:database/
    var routePrefix = "/db/" + db.name;

    // Use user section 
    app.use(routePrefix + "/user", user);

    // Connection callback - we need to wait for modules to initialize
    var connect = () => {
        // Initialize connection 
        connections[db.name] = new mongoose.Mongoose().createConnection(db.url);

        // Create some callbacks
        connections[db.name].on("connected", () => { console.log("Connected to database " + db.url); });
        connections[db.name].on("error", onDatabaseError)

        // Once we initialize connection, we need to setup all routes 
        connections[db.name].once("open", function () {
            // Load routes
            var routes = require('./app/routes');

            // Loop trough routes and use all of them
            _.each(routes, function (controller, route) {
                var newRoute = routePrefix + route;
                app.use(newRoute, controller(app, newRoute, db.name));
            });
        });
    };

    // Initialize models
    _.each(appModels, (model, index) => {

        // Create object if doenst exist
        if (app.models == null)
            app.models = {};

        if (app.models[db.name] == null) {
            app.models[db.name] = { [model.name]: model.model };
        }
        else {
            app.models[db.name] = Object.assign(app.models[db.name], { [model.name]: model.model });
        }

        processed++;

        // if this was the last process we are ready to connect 
        if (processed === appModels.length)
            connect();
    });
});

app.listen(3000);

app / models / index.js

module.exports = [
    {
        name: "navigation",
        model: require('./Navigation.js')
    },
    ...
];

app / routes.js

module.exports = {
  '/navigation': require('./controllers/NavigationController'),
  ....
};

app / controllers / NavigationController.js

var restful = require("node-restful");

module.exports = function(app, route, dbname){

    console.log(route);

    var rest = restful.model(
        "navigation",
        app.models[dbname].navigation
    ).methods(['get', 'put', 'post', 'delete']);

    rest.register(app, route);

    // Return middleware
    return function(req, res, next){
        next();
    };
};

Navigation.js基本上只是一个模式。如果我这样手动设置路线:

app.get("/db/:database/navigation", (req, res) => {

    var dbname = req.params.database;
    var conn = connections[dbname];
    var navs = conn.model("navigation", app.models[dbname].navigation);

    // Send json data/error
    if (navs) navs.find({}, (err, data) => res.json(data));
    else res.json({ error: true, msg: "Model not found" });
});

它工作正常。我想我需要将连接分配给某个地方以保持安静,但我不知道在哪里。如果我将单连接与mongoose.connect()结合使用,那么一切都将正常运行,但这不是我所需要的:)

有人知道下一步该怎么做吗?谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

深入研究并扩展了驱动程序引用

这是所有的更改,希望对以后的人有所帮助:)

扩展程序/restful/index.js

var restful = require("node-restful"),
model = require("./model"),
mongoose = require('mongoose');

exports = module.exports = restful;
exports.model = model;
exports.mongoose = mongoose;

扩展/restful/model.js

exports = module.exports = model; 
exports.changeDriver = function(driver){
    mongoose = driver; 
}
// original model function from node-restful/lib/model.js
function model() {
    var result = mongoose.model.apply(mongoose, arguments),
        default_properties = defaults();
    if (1 === arguments.length) return result;

    for (var key in default_properties) {
       result[key] = default_properties[key];
    }

    return result; 
}

app / controllers / navigation.js

var restful = require("../extensions/restful");

module.exports = function(app, route, db)
{
    restful.model.changeDriver(db.mongoose);

    // Setup controller REST
    var rest = restful.model(
        "navigation",
        app.models[db.name].navigation
    ).methods(['get', 'put', 'post', 'delete']);

    // Register this endpoint with the application
    rest.register(app, route);

    // Return middleware
    return function(req, res, next){
        next();
    };
};

index.js

....
var connect = () => {

        // Initialize connection        
        var $db = databases[_db.name] = {
            mongoose: new mongoose.Mongoose(), 
            name: _db.name
        };

        $db.mongoose.connect(_db.url);

        // Create some callbacks
        $db.mongoose.connection.on("connected", () => { console.log("Connected to database " + _db.url); });
        $db.mongoose.connection.on("error", (err) => { console.log("Database error: " + err); });

        // Once we initialize connection, we need to setup all routes 
        $db.mongoose.connection.once("open", function () {

            // Custom routes for user section
            var userRoutes = new UserRoutes($db.mongoose);   
            app.use(routePrefix + "/user", userRoutes.getRouter());

            // Load routes
            var routes = require('./app/routes');

            // Loop trough routes and use all of them
            _.each(routes, function (controller, route) {
                var newRoute = routePrefix + route;
                app.use(newRoute, controller(app, newRoute, $db));
            });
        });
    };
....