我正在使用 MEAN 和 ionic 框架制作一个应用程序,其中 nodejs 是连接到数据库 (mongoDb) 的中间件。我需要使用 node server.js
运行 nodejs 服务器,并使用 ionic serve
运行应用程序。这是我的 server.js。
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
CohortController =require('./www/server/controller/CohortController');
mongoose.connect('mongodb://localhost:27017/persistent');
app.use(bodyParser());
app.get('/api/cohorts',CohortController.list);
app.post('/api/cohorts',CohortController.create);
app.listen(3000,function(){
console.log('Listening...');
})
现在这是我的 app.js。我使用 http://localhost:3000
来获取 JSON。
app.controller('CohortController',['$scope','$resource',
function($scope,$resource){
var Cohort=$resource('http://localhost:3000/api/cohorts');
Cohort.query(function(results){
$scope.cohorts=results;
});
$scope.cohorts=[];
$scope.createCohort= function () {
var cohort=new Cohort();
cohort.name=$scope.CohortName;
cohort.id=$scope.CohortId;
cohort.$save(function(result){
$scope.cohorts.push(result);
$scope.CohortName='';
$scope.CohortId='';
});
}
}]);
将 Node 服务器转为移动应用程序后,如何运行 Node 服务器?应用程序将如何使用 API?
最佳答案
您必须让您的 Node.js 应用程序在服务器上运行,然后您可以通过它的公共(public) IP 访问(从您的 Ionic 应用程序)。因此,您不会使用 http://localhost:3000
来获取 JSON,而是使用类似 http://123.456.789.123:3000
的方式。
但是,通常情况下,这不是您执行此操作的方式(使用端口 3000)。您还需要做的是(例如)将 Nginx 放在您的 Node.js 应用程序 ( see an example here ) 前面,以便从标准 HTTP 端口 (80) 为您的 api 提供服务。
所以,基本上,您实际上不能“在 Ionic 应用程序中运行 Node.js 服务器”——您的做法是将 Node.js 应用程序与 Ionic 分开运行,并通过标准化 API 公开其功能(通常是现在REST 是你想要实现的),然后你通过 Ionic 的(好吧,准确地说,它实际上是 Angular 的)$resource module “消费”它。
希望这有助于澄清一些问题。
关于node.js - 如何在 Ionic 移动应用程序中运行 Node.js 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34579550/