CSS不使用Node.js和express.static加载

zhte4eai  于 2023-04-01  发布在  Node.js
关注(0)|答案(1)|浏览(80)

我目前正在使用Node.js和Express进行一个Web项目,我遇到了一个问题,在提供静态文件时,我的CSS无法正确加载。我尝试使用express.static,但它似乎无法按预期工作。下面是我的文件夹结构和代码的简要概述:

const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
const port = 3000;

app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, '..', 'Public')));

app.post('/subscribe', (req, res) => {
  const email = req.body.email;
  
  fs.appendFile('subscribers.txt', email + '\n', (err) => {
    if (err) throw err;
  });

  res.send('Thank you for subscribing!');
});

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '..', 'Public', 'Home', 'Home.html'));
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
    <link rel="stylesheet" type="text/css" href="Home.css">
    <script src="https://kit.fontawesome.com/3720a64a77.js" crossorigin="anonymous"></script>
</head>
{
  "name": "email-subscription",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.20.2",
    "express": "^4.18.2"
  }
}

我是新的编码,所以深深感谢任何帮助/建议!

wz3gfoph

wz3gfoph1#

Express服务器正在为整个Public目录提供服务,但CSS文件Home.css位于Public/Home/Home.css中,因此需要使用路径Home/Home.css(相对于所提供的目录,而不是相对于HTML文件)来获取CSS文件
只需在HTML中更改这一行:

<link rel="stylesheet" type="text/css" href="Home.css">

改为:

<link rel="stylesheet" type="text/css" href="/Home/Home.css">

相关问题