在Node JS Controller

时间:2015-07-03 00:12:08

标签: node.js express parse-platform

我正在尝试使用Parse.com构建Node JS + Express Web应用程序。我在我的服务器js中有这个:

var express = require('express'),
    app = express(),
    bodyParser = require('body-parser'),
    Parse = require('parse').Parse;
    projects = require('./controllers/projects');

// Parse fun
Parse.initialize('MY_APP_ID_HERE', 'MY_JS_KEY');

app.use(bodyParser.urlencoded({ extended: false }));

app.get('/projects',projects.index);
app.get('/projects/new',projects.new);

app.listen(9000);

现在在我的项目控制器中:

module.exports.create = function(req,res){
    var projectObject = Parse.Object.extend("ProjectObject");
    var project = new projectObject();
    project.save(req.body).then(function(object) {
        res.redirect('/projects');
    });
};

module.exports.index = function(req,res){
    var projectObject = Parse.Object.extend("ProjectObject");
    var query = new Parse.Query(projectObject);
    query.limit(100);
    query.first({
        success: function(projects) {
            // Successfully retrieved the projects.
            res.json(projects);
        },
        error: function(error) {
            console.log("Error: " + error.code + " " + error.message);
        }
    });
};

这是我得到的错误:

ReferenceError:未定义Parse    在module.exports.create([REST_OF_PATH_REMOVED] /app/controllers/projects.js:5:22)    在Layer.handle [as handle_request]([REST_OF_PATH_REMOVED] /app/node_modules/express/lib/router/layer.js:95:5)    在下一步([REST_OF_PATH_REMOVED] /app/node_modules/express/lib/router/route.js:131:13)    在Route.dispatch([REST_OF_PATH_REMOVED] /app/node_modules/express/lib/router/route.js:112:3)    在Layer.handle [as handle_request]([REST_OF_PATH_REMOVED] /app/node_modules/express/lib/router/layer.js:95:5)    在[REST_OF_PATH_REMOVED] /app/node_modules/express/lib/router/index.js:277:22    在Function.process_params([REST_OF_PATH_REMOVED] /app/node_modules/express/lib/router/index.js:330:12)    在下一步([REST_OF_PATH_REMOVED] /app/node_modules/express/lib/router/index.js:271:10)    在[REST_OF_PATH_REMOVED] /app/node_modules/body-parser/lib/read.js:121:5    完成后([REST_OF_PATH_REMOVED] /app/node_modules/body-parser/node_modules/raw-body/index.js:233:14)

2 个答案:

答案 0 :(得分:0)

简单的回答是移动

var Parse = require('parse').Parse;

Parse.initialize('MY_APP_ID_HERE', 'MY_JS_KEY');

到您的项目控制器。根据发布的代码,您的server.js文件中不需要它们。

答案 1 :(得分:0)

Parse不属于fn的范围。你可以按照之前的建议把声明带到你的控制器上,或者(虽然不是一个好的做法)让Parse成为一个全局的(只要小心不要覆盖应用程序其他部分的变量)

app.js

...

global.Parse = require('parse').Parse;

...

controller.js

...

new Parse.query ...

...