Express.js index.js 404(Not Found)

出于某种原因,它无法加载我的index.html引用的index.js脚本。 server.js,index.html和index.js都位于我的项目文件夹的根目录。

server.js

var express = require('express'), app = express(); app.set("view options", {layout: false}); app.use(express.static(__dirname + '/public')); app.set('views', __dirname + '/'); app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); app.get('/', function (req, res) { res.render('index.html'); }); app.listen(4000, function () { console.log('Example app listening on port 4000!'); }); 

的index.html

 <html> </head></head> <body> <div class="ink-grid vertical-space"> <div id="content"> <div class="panel vertical-space"> <div id="app"/> </div> </div> </div> <script type="text/babel" src="index.js"></script> </body> </html> 

你必须提供这些文件。 你可以单独做:

 app.get('/index.js', function (req, res) { res.sendFile('index.js'); }); 

或者创build一个目录(例如www ),用于你想要的所有服务并使用express.static

 app.use(express.static('www')); 

通过查看声明

 app.use(express.static(__dirname + '/public')); 

你的index.js文件应该在public目录下。

由于index.jsserver.js在同一个目录下,所以定义

 app.use(express.static(.));