我正在尝试在顶级Express js上创建一个angular7应用。我正在使用命令
ng build --watch
以便将渲染的文件映射为存储在服务器/公共目录中
下面是我用于快递的app.js代码
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 users = require('./routes/users');
var app = express();
// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'pug');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
// 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('abcd',function(req, res, next){
return res.sendFile(app.get('public') + '/index.html');
});
app.use('/',function(req, res, next){
return res.sendFile(app.get('public') + '/index.html');
});
// app.use('/', index);
// app.use('/users', users);
// 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;
这个想法是将所有路由路由到index.html文件。我有一条路线abcd,如果我尝试使用ng serve(角度7的开发模式),则可以正常使用。
i.e localhost:4200/abcd - works fine
但是在快递服务器上
localhost:3000/abcd - it is not working
我收到以下错误
Error: Failed to lookup view "error" in views directory "E:\ngME\server\views"
at Function.render (E:\ngME\server\node_modules\express\lib\application.js:580:17)
at ServerResponse.render (E:\ngME\server\node_modules\express\lib\response.js:971:7)
at E:\ngME\server\app.js:50:7
at Layer.handle_error (E:\ngME\server\node_modules\express\lib\router\layer.js:71:5)
at trim_prefix (E:\ngME\server\node_modules\express\lib\router\index.js:315:13)
at E:\ngME\server\node_modules\express\lib\router\index.js:284:7
at Function.process_params (E:\ngME\server\node_modules\express\lib\router\index.js:335:12)
at next (E:\ngME\server\node_modules\express\lib\router\index.js:275:10)
at Layer.handle_error (E:\ngME\server\node_modules\express\lib\router\layer.js:67:12)
at trim_prefix (E:\ngME\server\node_modules\express\lib\router\index.js:315:13)
如何使localhost:3000 / abcd工作?我不想在有角的末端使用哈希。
答案 0 :(得分:0)
弄清楚了。该代码应该是
app.use('*',function(req, res, next){
return res.sendFile(__dirname + '/public/index.html')
});