使用 Express 时未加载 Javascript (Angular)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23860275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript (Angular) not loading when using Express
提问by user2669464
I'm trying to get my application deployed to a public domain using node.js, express.js, and Heroku (or Modulus.io).
我正在尝试使用 node.js、express.js 和 Heroku(或 Modulus.io)将我的应用程序部署到公共域。
Everything was working fine in the development environment. But when I try to deploy it to Heroku or Modulus, I run into a lot of problems with PORT and Express. Right now I'm trying to deploy to Heroku.
在开发环境中一切正常。但是当我尝试将它部署到 Heroku 或 Modulus 时,我遇到了很多 PORT 和 Express 问题。现在我正在尝试部署到 Heroku。
The project is built on angular-seed, and I made a few changes to package.json and how the server starts in order for it to work with Heroku.
该项目基于 angular-seed,我对 package.json 以及服务器的启动方式进行了一些更改,以便它与 Heroku 一起使用。
Right now, the local server (localhost:5000) loads a static HTML page (index.html works fine), but none of the CSS or Javascript is being loaded to the page. Same thing with the deployed app on Heroku.
现在,本地服务器 (localhost:5000) 加载了一个静态 HTML 页面(index.html 工作正常),但是没有任何 CSS 或 Javascript 被加载到页面上。与 Heroku 上部署的应用程序相同。
Here are the changes I made to package.json (from the one provided in angular-seed):
以下是我对 package.json 所做的更改(来自 angular-seed 中提供的更改):
...
"scripts": {
"start": "node web.js",
...
"main": "web.js",
...
Here is what web.js looks like:
这是 web.js 的样子:
var express = require("express");
var logfmt = require("logfmt");
var app = express();
app.use(logfmt.requestLogger());
app.use(express.static(__dirname + '/app'));
app.get('/', function(req, res) {
//res.send('Hello World!');
res.sendfile('./app/index.html');
});
var port = Number(process.env.PORT || 5000);
app.listen(port, function() {
console.log("Listening on " + port);
});
In the HTML index file,
在 HTML 索引文件中,
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>Title</title>
<link rel="stylesheet" href="css/app.css"/>
</head>
<body>
...
<script src="../bower_components/angular/angular.js"></script>
<script src="../bower_components/angular-route/angular-route.js"></script>
<script src="../bower_components/angular-sanitize/angular-sanitize.js"></script>
<script src="../bower_components/angular-animate/angular-animate.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
</body>
</html>
I start the server using "foreman start" in the command prompt and it loads the local server just fine with the plain HTML. I've also tried using instead:
我在命令提示符下使用“foreman start”启动服务器,它用纯 HTML 加载本地服务器就好了。我也试过使用:
app.configure(function() {
app.use(express.static(__dirname + '/public'));
app.use(express.logger('dev'));
app.use(express.bodyParser());
});
in web.js, but when I start the server, I get an error saying "TypeError: undefined is not a function" pointing at the period at "app.configure".
在 web.js 中,但是当我启动服务器时,我收到一条错误消息,指出“类型错误:未定义不是函数”,指向“app.configure”的句点。
The error in the console says:
控制台中的错误说:
GET http://localhost:5000/bower_components/angular/angular.js 404 (Not Found) localhost/:22
GET http://localhost:5000/bower_components/angular-route/angular-route.js 404 (Not Found) localhost/:23
GET http://localhost:5000/bower_components/angular-sanitize/angular-sanitize.js 404 (Not Found) localhost/:24
GET http://localhost:5000/bower_components/angular-animate/angular-animate.js 404 (Not Found) localhost/:25
Uncaught ReferenceError: angular is not defined
... etc
I've been trying to Google a solution, but most of them are from a year ago which does not seem to work anymore. Any help is appreciated. Thanks!
我一直在尝试谷歌一个解决方案,但其中大部分是一年前的,似乎不再有效。任何帮助表示赞赏。谢谢!
Followup error: Now I can't push it to Heroku. Everything works fine locally though. Here's terminal output when I try to push it to Heroku:
后续错误:现在我无法将其推送到 Heroku。不过在本地一切正常。这是我尝试将其推送到 Heroku 时的终端输出:
Counting objects: 5, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 285 bytes | 0 bytes/s, done.
Total 3 (delta 2), reused 0 (delta 0)
To ssh://[email protected]/[...]
a655423..98d78e4 master -> master
user@ubuntu:~/directory$ git push heroku
warning: push.default is unset; its implicit value is changing in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the current behavior after the default changes, use:
git config --global push.default matching
To squelch this message and adopt the new behavior now, use:
git config --global push.default simple
See 'git help config' and search for 'push.default' for further information.
(the 'simple' mode was introduced in Git 1.7.11. Use the similar mode
'current' instead of 'simple' if you sometimes use older versions of Git)
Fetching repository, done.
Counting objects: 5, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 285 bytes | 0 bytes/s, done.
Total 3 (delta 2), reused 0 (delta 0)
-----> Node.js app detected
PRO TIP: Specify a node version in package.json
See https://devcenter.heroku.com/articles/nodejs-support
-----> Defaulting to latest stable node: 0.10.21
-----> Downloading and installing node
-----> Restoring node_modules directory from cache
-----> Pruning cached dependencies not specified in package.json
-----> Node version changed since last build; rebuilding dependencies
> [email protected] install /tmp/build_f31706d9-b302-4cdd-ae3e-cce981c1bf51/node_modules/karma/node_modules/socket.io/node_modules/socket.io-client/node_modules/ws
> (node-gyp rebuild 2> builderror.log) || (exit 0)
make: Entering directory `/tmp/build_f31706d9-b302-4cdd-ae3e-cce981c1bf51/node_modules/karma/node_modules/socket.io/node_modules/socket.io-client/node_modules/ws/build'
CXX(target) Release/obj.target/bufferutil/src/bufferutil.o
SOLINK_MODULE(target) Release/obj.target/bufferutil.node
SOLINK_MODULE(target) Release/obj.target/bufferutil.node: Finished
COPY Release/bufferutil.node
CXX(target) Release/obj.target/validation/src/validation.o
SOLINK_MODULE(target) Release/obj.target/validation.node
SOLINK_MODULE(target) Release/obj.target/validation.node: Finished
COPY Release/validation.node
make: Leaving directory `/tmp/build_f31706d9-b302-4cdd-ae3e-cce981c1bf51/node_modules/karma/node_modules/socket.io/node_modules/socket.io-client/node_modules/ws/build'
> [email protected] install /tmp/build_f31706d9-b302-4cdd-ae3e-cce981c1bf51/node_modules/karma-phantomjs-launcher/node_modules/phantomjs
> node install.js
Downloading http://cdn.bitbucket.org/ariya/phantomjs/downloads/phantomjs-1.9.7-linux-x86_64.tar.bz2
Saving to /tmp/phantomjs/phantomjs-1.9.7-linux-x86_64.tar.bz2
Receiving...
Error requesting archive.
Status: 403
Request options: {
"protocol": "http:",
"slashes": true,
"auth": null,
"host": "cdn.bitbucket.org",
"port": null,
"hostname": "cdn.bitbucket.org",
"hash": null,
"search": null,
"query": null,
"pathname": "/ariya/phantomjs/downloads/phantomjs-1.9.7-linux-x86_64.tar.bz2",
"path": "/ariya/phantomjs/downloads/phantomjs-1.9.7-linux-x86_64.tar.bz2",
"href": "http://cdn.bitbucket.org/ariya/phantomjs/downloads/phantomjs-1.9.7-linux-x86_64.tar.bz2"
}
Response headers: {
"content-type": "text/html",
"content-length": "14134",
"connection": "keep-alive",
"date": "Sat, 24 May 2014 00:28:20 GMT",
"last-modified": "Sat, 24 May 2014 00:08:24 GMT",
"etag": "\"999f4f548bfffe25245dc29e49c57e9c\"",
"accept-ranges": "bytes",
"server": "AmazonS3",
"age": "49096",
"x-cache": "Hit from cloudfront",
"via": "1.1 7718496b82dfc64dff52dbb3d7f07f3b.cloudfront.net (CloudFront)",
"x-amz-cf-id": "kA4IYvDWX-l2HNW8EzztjY9STY96Ns0vsZDWTUaloDmJTnwJakcDIg=="
}
Make sure your network and proxy settings are correct.
npm ERR! weird error 1
npm ERR! not ok code 0
! Push rejected, failed to compile Node.js app
Followup Error 2: Okay, that fixed the problem of not being able to push to Heroku. So now I can push changes to Heroku, but the AngularJS and CSS are still not displaying on the Heroku domain. I checked the console on the domain, which says:
后续错误 2:好的,解决了无法推送到 Heroku 的问题。所以现在我可以将更改推送到 Heroku,但是 AngularJS 和 CSS 仍然没有显示在 Heroku 域上。我检查了域上的控制台,上面写着:
GET http://myapp.herokuapp.com/bower_components/angular-sanitize/angular-sanitize.js 404 (Not Found) lit-inlet-8601.herokuapp.com/:24
GET http://myapp.herokuapp.com/bower_components/angular-animate/angular-animate.js 404 (Not Found) lit-inlet-8601.herokuapp.com/:25
Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:modulerr] Failed to instantiate module ngAnimate due to:
Error: [$injector:nomod] Module 'ngAnimate' is not available! You either misspelled the modul...<omitted>...1) angular.js:78
This is strange because it works fine locally. On the inspect element Sources tab, it seems to be missing some directories (namely, angular-animate and angular-sanitize). I tried running both "heroku run bower install angular-sanitize" and "heroku run bower install angular-animate" in the terminal but it didn't fix the problem.
这很奇怪,因为它在本地运行良好。在检查元素 Sources 选项卡上,似乎缺少一些目录(即 angular-animate 和 angular-sanitize)。我尝试在终端中同时运行“heroku run bower install angular-sanitize”和“heroku run bower install angular-animate”,但没有解决问题。
"foreman start" and "npm start" both start the server locally and everything displays as it should.
“foreman start”和“npm start”都在本地启动服务器,一切都按原样显示。
My index.html file is under the app_name/app/ directory and web.js is located in the app_name directory. I haven't changed any of the scripts to load Angular in the index.html file, so it still looks as listed above.
我的 index.html 文件位于 app_name/app/ 目录下,而 web.js 位于 app_name 目录中。我没有更改任何脚本来加载 index.html 文件中的 Angular,所以它看起来仍然如上所列。
My app.js file which is located in app_name/app/js should be listing the dependencies correctly:
我位于 app_name/app/js 中的 app.js 文件应该正确列出依赖项:
angular.module('myApp', [
'ngAnimate',
'ngSanitize',
'ngRoute',
'myApp.filters',
'myApp.services',
'myApp.directives',
'myApp.controllers'
])...
I am not sure what could be causing this. Any help is appreciated. Thanks!
我不确定是什么原因造成的。任何帮助表示赞赏。谢谢!
回答by Peter Lyons
You need another static directory route:
您需要另一个静态目录路由:
app.use(express.static(__dirname + '/app'));
//add this so the browser can GET the bower files
app.use('/bower_components', express.static(__dirname + '/bower_components'));
In order for deployment to work on heroku, you need to set up a postinstall
script in your package.json
file to heroku will run bower install
for you.
为了部署在 heroku 上工作,你需要postinstall
在你的package.json
文件中设置一个脚本,heroku 将为bower install
你运行。
Here's a blog post describing that.
"scripts": {
"postinstall": "./node_modules/bower/bin/bower install"
}
Because currently bower install
is not running, the actual angularjs files you need are not there, which causes these errors in the browser console, which causes the ReferenceError
about angular not being defined.
因为当前bower install
没有运行,你需要的实际angularjs文件不存在,导致浏览器控制台出现这些错误,导致ReferenceError
about angular没有被定义。
GET http://localhost:5000/bower_components/angular/angular.js 404 (Not Found) localhost/:22
GET http://localhost:5000/bower_components/angular-route/angular-route.js 404 (Not Found) localhost/:23
GET http://localhost:5000/bower_components/angular-sanitize/angular-sanitize.js 404 (Not Found) localhost/:24
GET http://localhost:5000/bower_components/angular-animate/angular-animate.js 404 (Not Found) localhost/:25
Uncaught ReferenceError: angular is not defined
Go step by step. First, make sure the files actually get properly installed both locally and on heroku. Then make sure they properly load into the browser. Then make sure your actual javascript code is correct for your application.
一步一步来。首先,确保文件实际上在本地和heroku 上都正确安装。然后确保它们正确加载到浏览器中。然后确保您的实际 javascript 代码对于您的应用程序是正确的。
Next Problem
下一个问题
Followup Error 2: Okay, that fixed the problem of not being able to push to Heroku. So now I can push changes to Heroku, but the AngularJS and CSS are still not displaying on the Heroku domain. I checked the console on the domain, which says:
后续错误 2:好的,解决了无法推送到 Heroku 的问题。所以现在我可以将更改推送到 Heroku,但是 AngularJS 和 CSS 仍然没有显示在 Heroku 域上。我检查了域上的控制台,上面写着:
GET http://myapp.herokuapp.com/bower_components/angular-sanitize/angular-sanitize.js 404 (Not Found) lit-inlet-8601.herokuapp.com/:24
GET http://myapp.herokuapp.com/bower_components/angular-animate/angular-animate.js 404 (Not Found) lit-inlet-8601.herokuapp.com/:25
Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:modulerr] Failed to instantiate module ngAnimate due to:
Error: [$injector:nomod] Module 'ngAnimate' is not available! You either misspelled the modul...<omitted>...1) angular.js:78
So both angular-sanitize and angular-animate are missing from heroku, which means the bower install
didn't install them. Verify you actually reference them properly in your bower.json
files.
因此,heroku 中缺少 angular-sanitize 和 angular-animate,这意味着bower install
没有安装它们。验证您确实在bower.json
文件中正确引用了它们。
回答by eunoia
Have you considered keeping your bower_components folder under version and control and if so have you checked your .gitignore? I just ran into a similar problem where certain bower installed dependencies were not loading after deployment. Turns out I was ignoring all dist/ folders.
您是否考虑过将 bower_components 文件夹置于版本和控制之下,如果是,您是否检查过 .gitignore?我刚刚遇到了一个类似的问题,其中某些 bower 安装的依赖项在部署后没有加载。原来我忽略了所有的 dist/ 文件夹。