问题描述
我遵循了有关在a2hosting上设置node.js的出色教程:https://www.youtube.com/watch?v=BAD5JyOymRg
除了CSS无法在Firefox或Chrome中加载并且由于某种原因引发503错误之外,其他所有内容似乎都可以正常工作。如果我将href
指向完全没有文件,它还会引发503错误。我尝试将href
链接更改为/stylesheets/style.css
或移动style.css,但是没有任何运气。
任何帮助将不胜感激!
server.js:
var express = require('express');
var app = express();
var path = require('path');
app.set('views',path.join(__dirname,'views'));
app.set('view engine','ejs');
app.use('/testapp/static',express.static('public'));
app.get('/testapp',(req,res) => {
res.render('index',{ title: 'Express' });
});
app.listen();
package.json:
{
"name": "app","version": "1.0.0","description": "My App","main": "app.js","scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},"dependencies": {
"express": "^6.14.7","ejs": "~2.6.1"
},"author": "","license": "ISC"
}
index.ejs:
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='http://*mysite*.com/testapp/static/stylesheets/style.css' />
</head>
<body>
<h1>Hello <%=title%></h1>
</body>
</html>
style.css:
body {
background-color: red;
}
这是文件夹结构:
testapp
-public
--stylesheets
---style.css
-views
--index.ejs
-server.js
-package.json
-node_modules
解决方法
-
请确保您的
testapp
是正确的应用程序URL(不是应用程序根目录) -
您的起始文件名为
server.js
,但是您的package.json引用了app.js
。您是否有一些其他文件可能会起作用,而不是您认为的文件?请检查应用程序启动文件是否正确。 - 检查
.htaccess
目录中的/home/<username>/public_html
文件配置
请让我知道某些选择是否有帮助,或者您需要其他信息或研究。
,如果您能够看到html而不是CSS,请尝试在指定目录位置的地方调整第二个参数。
app.use('/testapp/static',express.static('public'));
您提供给express.static函数的路径是相对于您启动节点进程(link)的目录的。
我提供了一个示例代码,您可以参考将一个文件夹放在目录内,将一个文件夹放在目录外的位置。 -https://codesandbox.io/s/sweet-grass-0dxvh?file=/testapp/server.js
,更改自
app.use('/testapp/static',express.static('public'));
到
app.use('/testapp/static',express.static(path.join(__dirname,'public')));
,
请像这样更改index.ejs
:
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='http://localhost:3000/testapp/static/stylesheets/style.css' />
</head>
<body>
<h1>Hello <%=title%></h1>
</body>
</html>
并像这样更改server.js
:
var app = express();
var path = require('path');
app.set('views',path.join(__dirname,'views'));
app.set('view engine','ejs');
app.use('/testapp/static',express.static('public'));
app.get('/testapp',(req,res) => {
res.render('index',{ title: 'Express' });
});
app.listen(3000);
我更改了以下几行:
index.ejs:
href ='http:// localhost:3000 / testapp / static / stylesheets / style.css'/>
server.js:
app.listen(3000);