[英]Node.JS and AngularJS Routes with API routes
So I am using Node.JS with Express as my backend and my servlet for API. 所以我使用Node.JS作为我的后端和我的servlet for API。 I'm using AngularJS as my front end.
我正在使用AngularJS作为我的前端。
Through many Google searches, I finally solved my problem of using ngRoute
with AngularJS and Node.js. 通过许多谷歌搜索,我终于解决了使用
ngRoute
与AngularJS和Node.js的问题。 And ended up with this: 结果是这样的:
var index = require('./routes/index');
var auth = require('./routes/auth');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.use('/api/auth', auth);
app.use('/', index);
app.use('*', index);
This is of course an excerpt of my app.js file at the root of my project. 这当然是我项目根目录下app.js文件的摘录。
Now when I make a call to my /api/auth/
I get told that node.js can't find my view. 现在当我调用我的
/api/auth/
我被告知node.js无法找到我的视图。 If I remove the app.use('*', index)
the API works again but 'ngRoute' doesn't work. 如果我删除
app.use('*', index)
,API会再次运行,但'ngRoute'不起作用。
How can I get to a point where both are working together? 我怎样才能达到两者合作的程度? I also want to keep the address bar url as clean as possible.
我还想保持地址栏网址尽可能干净。
My project was started with a call to yo node
using yeoman
if that helps any in the file/folder structure of my application. 我的项目是使用
yeoman
调用yo node
启动的,如果这对我应用程序的文件/文件夹结构有帮助的话。
Update 更新
I'm not getting any answers or comments so maybe providing my full app.js
file will be helpful and help me figure this out. 我没有得到任何答案或评论,所以也许提供我的完整
app.js
文件将有所帮助,并帮助我解决这个问题。 Here it is. 这里是。
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var auth = require('./routes/auth');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api/auth', auth);
app.use('/', index);
app.use('*', index);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Update 2 更新2
I have come to notice that the statement "ngRoute doesn't work" is vague. 我注意到“ngRoute不起作用”的说法含糊不清。 If I remove
app.use('*', index)
I receive this error if I try to go to an address other than the base address. 如果我删除
app.use('*', index)
如果我尝试去基地址以外的地址app.use('*', index)
我会收到此错误。 I also receive this error when trying to access the api/auth
尝试访问
api/auth
时,我也收到此错误
Error: Failed to lookup view "error" in views directory "/Users/mitch/websites/splatform/views"
Update 3 更新3
The index.js file that my routes in app.js refer to includes this as well. app.js中的路由所引用的index.js文件也包含此文件。
app.get('/', function(req, res, next) {
res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});
But, API calls shouldn't be going to the index.js File. 但是,API调用不应该转到index.js文件。 Should be going to Auth.js.
应该去Auth.js.
Update 4 更新4
As requested, here is my $routeProvider
from AngularJS. 根据要求,这是来自AngularJS的
$routeProvider
。
$routeProvider
.when('/', {
templateUrl: 'templates/home.html',
resolve: {
lazy: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load ('frontStyles');
}]
}
})
.when('/app/login', {
templateUrl: 'templates/login.html',
resolve: {
lazy: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load ('appStyles', 'appScripts');
}]
}
})
.when('/app/dashboard', {
templateUrl: 'templates/dashboard.html',
resolve: {
lazy: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load ('appStyles', 'appScripts');
}]
}
})
.otherwise({ redirectTo: '/' });
$locationProvider.html5Mode(true);
Also here is a simple run down of my file structure 这里还有一个简单的文件结构
app.js
routes
--auth.js
--index.js
views
--index.html ( angularJS Base )
public
--directives
--fonts
--images
--javascripts
--stylesheets
--templates ( Views that angularjs uses in `ng-view`
Call api's routes first then angularjs index. 首先调用api的路由然后调用angularjs索引。
For example: routesWeb.js 例如: routesWeb.js
'use strict';
var express = require('express');
var path = require('path');
module.exports = function(app) {
var path_web = path.resolve(__dirname, '..');
var path_origin = path.resolve(__dirname, '../../');
app.use('/scripts',express.static(path_web + '/scripts'));
app.use('/pages',express.static(path_web + '/pages'));
app.use('/node_modules',express.static(path_origin + '/node_modules'));
app.route('/*')
.get(function(req, res){
res.sendFile(path_web + '/pages/ng-index.html');
});
}
pessoaRota.js pessoaRota.js
'use strict';
module.exports = function(app) {
var pessoasCtrl = require('../controllers/pessoasController');
app.route('/api/pessoas')
.get(pessoasCtrl.obter_todos_pessoas);
app.route('/api/pessoas/:pessoaId')
.get(pessoasCtrl.obter_pessoa_por_id);
app.route('/api/pessoasFeias')
.get(pessoasCtrl.obter_pessoas_feias);
};
server.js server.js
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
app.use(bodyParser.json());
app.use(cookieParser());
var server = app.listen(port, function(){
var host = server.address().address;
var port = server.address().port;
console.log("Aplicação está on nesse endereço http://%s:%s", host, port)
});
require('./api/routes/pessoaRota.js')(app);
require('./web/routes/routesWeb.js')(app);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.