2017-03-18 30 views
2

我試圖運行基本MEAN應用。我的應用程序沒有使用Angular部分。 但是,當我包含Angular時,我看不到「view」文件夾中的HTML頁面。看不到我的html文件,鑑於

這是我的服務器:

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

var index=require('./routes/index'); 
var tasks=require('./routes/tasks'); 
var port=3000; 
var app=express(); 

/*View engine*/ 
app.set('views',path.join(__dirname, 'views')); 
app.set('view engine','ejs'); 
app.engine('html',require('ejs').renderFile); 

/*View static folder*/ 
app.use(express.static(path.join(__dirname, 'client'))); 

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

app.use('/',index); 
app.use('/api',tasks); 
app.listen(port, function(){ 
    console.log('The application is running on port '+port); 
}); 

這是 「路線」 目錄下我的索引路線:

var express=require('express'); 
var router=express.Router(); 

router.get('/',function(req, res, next){ 
    res.render('index.html'); 
}) 
module.exports=router; 

我的角碼是居住在客戶端/ app目錄。 我在終端的myapp/client目錄中輸入npm start。 我得到「無法獲取/」,並在終端,我看「404 GET /index.htm」明明

任何想法?

回答

3

這意味着,當你打開根路徑(/ URI),它會呈現index.html文件:

router.get('/',function(req, res, next){ 
    res.render('index.html'); 
}); 

,這意味着你的視圖文件(在你的問題index.html文件)位於views文件夾:

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

如果您希望index.html被EJS渲染,請將index.html文件放入views文件夾(而不是client文件夾)。

,並直接打開您的應用程序:http://localhost:3000/


附:如果你想打開index.html像這樣:http://localhost:3000/index.html

做以下操作:

確保您的routes/index.js有這樣的內容:

const 
    express = require('express'), 
    router = express.Router(); 

const renderViewFile = (filename) => (req, res) => res.render(filename); 

router.get('/', renderViewFile('index.html')); 
router.get('/index.html', renderViewFile('index.html')); 

module.exports = router; 

或:put index.html file into client folder and it will be served as static file

+0

我的index.html是下MYAPP \意見\而不是在MYAPP \意見\客戶端,它仍然無法正常工作:( –

+0

@TuviaKhusid好了,添加addtional航線服務'事實上日誌/ index.html'說你試圖訪問文件從瀏覽r像這樣:'http:// localhost:3000/index.html'當然是不可訪問的,cuz route'/ index.html'將由expressjs路由器按通常路由處理,當然不會被訪問,因爲的靜態中間件看起來'客戶端'文件夾 – num8er

+0

@TuviaKhusid檢查我最近更新的答案,希望它適合您的需要 – num8er