首页 > 解决方案 > CSS 在 a2hosting 上使用 node.js 引发 503 错误

问题描述

我遵循了关于在 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();

包.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"
}

索引.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>

样式.css:

body {
   background-color: red;
}

这是文件夹结构:

testapp
-public
--stylesheets
---style.css
-views
--index.ejs
-server.js
-package.json
-node_modules

标签: cssnode.jsexpresshosting

解决方案


如果您能够看到 html 而不是 CSS,请尝试调整您指定目录位置的第二个参数。

app.use('/testapp/static', express.static('public'));

您提供给 express.static 函数的路径是相对于您启动节点进程的目录(链接)。

我提供了一个示例代码,您可以参考我在目录中放置一个文件夹和在外部放置一个文件夹的位置。- https://codesandbox.io/s/sweet-grass-0dxvh?file=/testapp/server.js


推荐阅读