带有Node.js和parse.com后端的AngularJS SPA

时间:2016-01-15 20:06:31

标签: javascript angularjs node.js parse-platform

我有这个带有ui-router的AngularJS SPA,效果很好。它使用parse.com作为后端,我让它在常规Apache服务器上工作。

现在我想将它移到node.js服务器应用程序,我希望node.js处理parse.com的所有CRUD。

我设置了一个很好的小node.js应用程序作为服务器,它可以工作。

我的问题是:我如何处理node.js server-app和AngularJS SPA之间的请求?

我已经包含了我的server.js文件,万一有人可以使用它。



// set up =====================================================================================================
var express			= require('express'),
	path			= require('path'),
	morgan			= require('morgan'),
	bodyParser		= require('body-parser'),
	methodOverride	= require('method-override'),
	routes			= require('routes'),
	keys			= require('./config/keys'),
	port			= 80;

var app = express();

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

// view engine setup ==========================================================================================
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// configuration ==============================================================================================
app.use(require('prerender-node').set('prerenderToken', keys.prerender));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({'extended':'true'}));            // parse application/x-www-form-urlencoded
app.use(bodyParser.json());                                     // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride());
app.use(express.static(path.join(__dirname, 'public_html')));

Parse.initialize(keys.app, keys.js);

// routing ====================================================================================================
app.use(function(req, res) {
	"use strict";
    // use res.sendfile, as it streams instead of reading the file into memory. ===============================
    res.sendfile(__dirname + '/public_html/index.html');
});

app.use('/', routes);

// catch 404 and forward to error handler =====================================================================
app.use(function(req, res, next) {
	"use strict";
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// listen (start app with node server.js) =====================================================================
app.listen(port);
console.log("App listening on port %d", port);




文件结构:

- public_html/ <-- the angularjs app -->
- node_modules/ <-- installed modules for node -->
- config/
    - keys.js
- server.js
- package.json

当前设置

所以,目前,我会处理我的(angularjs)app控制器中的parse.com数据 - 其中一些是解析的云代码。

现在,我想将所有parse.com交易移至我的node.js服务器应用程序,以便我的angularjs&#34;调用&#34; node.js服务器应用程序,反过来&#34;调用&#34; parse.com获取我需要的数据,然后将其返回到angularjs应用程序,以便我可以更新我的视图(使用来自parse.com的新数据)。

我想要的例子

parse.com <--> node.js server-app <--> angularjs SPA (views)

我在控制器中做的一件简单事就是

&#13;
&#13;
var Profile = Parse.Object.extend('Profile');
var query = new Parse.Query(Profile);
query.equalTo('objectId', $stateParams.authorPermaLink);
query.find().then(function(results){
  var object = results[0];
  $scope.authorObj = results[0];
  $scope.template.pageName = object.get('screenname');
  $scope.template.pageAuthor = object.get('screenname');
  $scope.template.pagePublished = object.createdAt;
  $scope.template.pageLastEdit = object.updatedAt;
  $scope.$apply();
}, function(error){
  // error-handling
  console.log("Error: " + error.code + " " + error.message);
});
&#13;
&#13;
&#13;

现在,将这段代码移动到node.js很简单,因为我可以直接在node.js中使用parse.com SDK。但是如何让angularjs应用程序与node.js server-app进行通信?

1 个答案:

答案 0 :(得分:0)

好的,所以我设法以此为中心。

解决方案是制作将处理来自angularjs app的http请求的路由。

routes.js(node):

&#13;
&#13;
app.get('/api/article/:permalink', function(req, res) {
    blog.getArticle(req.params.permalink, function(data) {
        res.json(data);
    });
});


// everything else
app.use(function(req, res) {
  // use res.sendfile, as it streams instead of reading the file into memory.
  res.sendfile('./public_html/index.html');
});
&#13;
&#13;
&#13;

然后使用上面调用的blog对象和方法创建一个模型。

model.js(也是节点):

&#13;
&#13;
module.exports = {

  getArticle : function(permalink, callback) {
    "use strict";
    var Article = Parse.Object.extend('Article');
    var query = new Parse.Query(Article);
    query.include('category');
    query.include('profile');
    query.equalTo('permalink', permalink);
    query.find().then(function(results) {
      var result = results[0];
      var object = {
        title: result.get('title'),
        screenname: result.get('profile').get('screenname'),
        profileID: result.get('profile').id,
        content: result.get('content'),
        publishedAt: result.get('publishedAt'),
        updatedAt: result.updatedAt,
        categoryName: result.get('category').get('categoryName'),
        categoryPermaLink: result.get('category').get('categoryPermaLink'),
        articleID: result.id
      };

      callback(object);
      
    }, function(error) {
      callback({error: error});
    });
  }

};
&#13;
&#13;
&#13;

最后在mu angularjs应用程序中,只需发出一个http请求(在这个例子中得到,但其他动词也都可以工作)。

controller.js(angularjs):

&#13;
&#13;
$http.get('/api/article/' + $stateParams.articlePermaLink
         ).then(function successCallback(response) {
  response = response.data;
  $scope.articleTitle = response.title;
  $scope.template.pageName = response.title;
  $scope.articleAuthor = response.screenname;
  $scope.template.pageAuthor = response.screenname;
  $scope.profilePermaLink = response.profileID;
  $scope.articleContent = response.content;
  $scope.publishDate = response.publishedAt;
  $scope.template.pagePublished = response.publishedAt;
  $scope.template.pageLastEdit = response.updatedAt;
  $scope.category = response.categoryName;
  $scope.categoryPermaLink = response.categoryPermaLink;
  $scope.currentArticle = response.articleID;

  console.log(response.commentObj);

}, function errorCallback(response) {
  console.log("Error: " + response.code + " " + response.message);
});
&#13;
&#13;
&#13;

回调是神奇的!