无法从angular2中的视图文件夹中呈现index.html文件

时间:2017-03-29 13:31:31

标签: javascript node.js angular

我正在创建一个MEAN Stack应用程序,其中angular已在/client文件夹中设置。我希望当我在npm start文件夹中运行/client命令时,它应该从index.html文件夹中呈现/views文件,我错误地收到此错误

Cannot GET /

文件夹结构如下。

meanApp

-----客户端(angluar2在这里设置,但没有index.html文件)

---------- app

-----观看

----------的index.html

-----路线

----- server.js

server.js中的代码

var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");

var index =  require('./routes/index');
var tasks = require("./routes/tasks");

var app = express();

//View engines

app.set("views", path.join(__dirname,'views'));

app.set("view engine", 'ejs');

app.engine("html", require("ejs").renderFile);

//Set static folder

app.use(express.static(path.join(__dirname,'client')));

// Body parser

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({extended:false}));

app.use('/', index);

app.use('/index', index);

app.use('/api', tasks);

//listen

app.listen(3000, function(){

    console.log("Server listing @ 3000");

});

2 个答案:

答案 0 :(得分:1)

在这里,您需要为快速服务器定义路由,如:

app.set('appPath', 'client'); //this is a folder where your index.html is

app.route('/*')
    .get(function(req, res) {
      res.sendfile(app.get('appPath') + '/index.html');
    });

这将导致broweser中的每个调用都呈现索引文件。

答案 1 :(得分:0)

const http = require('http');
fs = require('fs');
var express = require('express');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var app = express();

app.set('appPath', 'views');
app.use(express.static(__dirname + '/views'));

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(expressValidator());

app.use('/*', function(req, res, next) {
    res.sendfile(app.get('appPath') + '/index.html');
});

http.createServer(app).listen(3001, function() {
    console.log(`Express server listening on port 3001`);
});

exports = module.exports = app;