我对this Angular2 GitHub sample app做了一些小修改,以便它使用Express而不是KOA。但问题是,当加载应用程序的根URL时,FireFox会在控制台中出现以下错误:
GET http://localhost:8080/vendor.js [HTTP/1.1 200 OK 16ms]
GET http://localhost:8080/boot.js [HTTP/1.1 200 OK 16ms]
The stylesheet http://localhost:8080/boot.css was not loaded because its MIME type, "text/html", is not "text/css". localhost:8080
SyntaxError: expected expression, got '<' vendor.js:1:0
SyntaxError: expected expression, got '<' boot.js:1:0
GET http://localhost:35729/livereload.js [HTTP/1.1 200 OK 9ms]
GET http://localhost:35729/livereload [HTTP/1.1 101 Switching Protocols 2ms]
似乎浏览器无法在应用中读取ES6。在示例应用程序中,Babel用于将ES6编译为浏览器可读的形式。我没有更改gulpfile.js
或router.js
,server/index.js
和package.json
以外的任何内容。但不知何故,服务index.html
不会给客户任何可以阅读的东西。
从Express.js提供ES6 / Angular2应用程序的正确方法是什么?需要对下面的代码进行哪些具体更改才能在修改后的GitHub示例中解决这些控制台错误?
以下是router.js
中两个版本的快速路线,每个版本都会产生上述相同的错误:
版本1:
'use strict';
// expose the routes to our app with module.exports
module.exports = function(app) {
//other routes omitted for brevity
app.get('*', function(req, res) {
console.log('inside / route!');
res.sendfile(path.resolve('dist/client/index.html')); // load the single view file (angular will handle the front-end)
});
};
版本2:
'use strict';
// expose the routes to our app with module.exports
module.exports = function(app) {
//other routes omitted for brevity
app.get('*', function(req, res) {
console.log('inside / route!');
res.sendfile(path.resolve('client/index.html')); // load the single view file (angular will handle the front-end)
});
};
正在解决问题吗index.html
?有没有更好的方法将应用程序从Express发送到浏览器?
新的server/index.js
是:
// set up ======================================================================
var express = require('express');
var app = express(); // create our app w/ express
var port = process.env.PORT || 8080; // set the port
var morgan = require('morgan'); // log requests to the console (express4)
var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
app.use(express.static(__dirname + '/client')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride());
app.use('/scripts', express.static(__dirname + '/node_modules/'));
// load the routes
require('./router')(app);
// listen (start app with node server.js) ======================================
app.listen(port);
console.log("App listening on port " + port);
唯一更改的其他文件是package.json
,但为了简洁起见,我在此省略它,因为它只列出了新的依赖项。如果有人真正关注这个问题,我可以发帖。