我正在使用Angular和express。当我尝试刷新不是主'/'
的页面时遇到问题,例如注册页面http://localhost:3000/register
它给我找不到404错误页面。
然后我将此代码添加到我的server.js(快速文件)
app.all('/*', function(req, res) {
res.sendfile('public/index.html');
});
但我下雪总是重定向到根网址。我希望当我刷新页面以刷新我所在的页面并再次给我相同的页面时。
我的server.js文件是
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var passport = require('passport');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
//connect to mongodb
require('./models/user.js');
require('./models/item.js');
mongoose.connect("mongodb://localhost:27017/web-shop");
var index = require('./routes/index');
var api = require('./routes/api');
var authenticate = require('./routes/authenticate')(passport);
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(session({
secret: 'super duper secret'
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(passport.session());
//Initialize Passport
var initPassport = require('./passport-init');
initPassport(passport);
app.use('/', index);
app.use('/api', api);
app.use('/auth', authenticate);
app.all('/*', function(req, res) {
res.sendfile('public/index.html');
});
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
这是我的角度路线
app.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'main.html',
controller: 'itemController'
})
.when('/login', {
templateUrl: 'login.html',
controller: 'authController'
})
.when('/register', {
templateUrl: 'register.html',
controller: 'authController'
})
.when('/add_item', {
templateUrl: 'dashboard.html',
controller: 'itemController'
})
$locationProvider.html5Mode(true);
})
答案 0 :(得分:1)
app.all('/*', function(req, res) {
res.sendfile('public/index.html');
});
删除app.use('/',index);它应该工作正常,因为它不允许上面的路由发送index.html每次遇到除“和”之外的路由