Node.js/angular.js - не может GET
У меня есть корневой маршрут, и он отлично работает. У меня также есть другой маршрут 127.0.0.1:3000/dashboard, если я просто набираю этот URL-адрес в адресной строке. Я получаю эту ошибку:
Невозможно GET/dashboard
Если я создаю ссылку на тот же URL-адрес, он отлично работает.
Если я обновляю эту страницу, я снова получаю ту же ошибку.
Ниже мой маршрут node.js
app.js
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, stats = require('./routes/stats')
, tests = require('./routes/test')
, http = require('http')
, util = require('util')
, path = require('path');
var app = module.exports = express();
app.configure(function(){
/*
* Configuration
*
*/
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
/*
* Middleware definitions
*
*/
app.use(express.favicon());
app.use(express.logger('dev'));
/*
* Error handling middleware
*/
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('shhhhhhhh, super secret'));
app.use(app.router);
// serves up dynamic css files
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(require('less-middleware')({ src: __dirname + '/public' }));
// serves a static path
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
/*
* Endpoints
*/
app.get('/', routes.index);
app.get('/test', tests.get);
app.post('/test', tests.post);
app.options('/test', tests.options);
app.get('/stats/sends', stats.sends.get);
app.get('/stats/events', stats.events.get);
app.get('/stats/attempts', stats.attempts.get);
app.get('/stats/errors', stats.errors.get);
app.get('/stats/mquad', stats.mquad.get);
app.get('/partials/:name', routes.partials);
app.get('/index/landing', routes.landing);
app.get('/index/dashboard', routes.dashboard);
console.log('Env: ' + app.settings.env);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
маршруты/index.js
exports.dashboard = function(req, res){
res.render('dashboard');
};
Angular маршрут
'use strict';
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives']).
config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/landing',
controller: LandingCtrl
}).
when('/dashboard', {
templateUrl: 'partials/dashboard',
controller: DashboardCtrl
}).
otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}]);
Ответы
Ответ 1
Причина, по которой это не работает, заключается в том, что ваш сервер не ловит все остальные маршруты и маршрутизирует их на одностраничное приложение, которое обслуживается routes.index
.
Чтобы поймать все остальные маршруты и направить их на индексную страницу, чтобы ваше приложение angular могло видеть, соответствует ли он прилагаемому URL-адресу, все, что вам нужно сделать, это добавить следующую строку после объявления последнего маршрута:
app.get('*', routes.index);
Теперь вы сможете:
- перейдите непосредственно к URL-адресу, который будет отправлен вашим Angular.js-приложением
- обновить любую страницу без ошибок
Ответ 2
Эта статья может помочь:
http://jjt.io/2013/11/16/angular-html5mode-using-yeoman-generator-angular/
В двух словах:
npm install --save-dev connect-modrewrite
Gruntfile:
connect: {
options: {
// ...
// Modrewrite rule, connect.static(path) for each path in target base
middleware: function (connect, options) {
var optBase = (typeof options.base === 'string') ? [options.base] : options.base;
return [require('connect-modrewrite')(['!(\\..+)$ / [L]'])].concat(
optBase.map(function(path){ return connect.static(path); }));
}
}
}
Ответ 3
Маршрут app.get('/index/dashboard', routes.dashboard);
относится к http://hostname/index/dashboard
, тогда как when('/dashboard', { ... })
относится к http://hostname/dashboard
.
Вы должны исправить маршрут: app.get('/dashboard', routes.dashboard);
Ответ 4
Я бы предложил довольно быстрое javascript-решение в передней и задней части.
NodeJs
// set up our one route to the index.html file
app.get('*', function (req, res){
res.sendFile(path.join(__dirname+'/public/index.html'));
});
Этот код сообщает локальному/удаленному серверу, где находится основной html, поэтому он может найти остальные шаблоны.
AngularJs
// If 404 Redirect to home
$routeProvider.otherwise( { redirectTo: '/'} );
Это также очень полезно, поэтому никогда не переходите к отсутствующей странице.