简体   繁体   English

express.js 公用文件夹未被识别

[英]express.js public folder not being recognised

I have developed a simple server in Node.js using Express and I have set the public folder to serve static files.我使用 Express 在 Node.js 中开发了一个简单的服务器,并且我设置了public文件夹来提供 static 文件。

In my root index.js , I have the following code:在我的根index.js中,我有以下代码:

const express = require('express');
const app = express();
const http = require('http').Server(app);
const fs = require('fs');

app.use(express.static(__dirname + '/public'));

app.get('/', (req, res) =>  {
    res.sendFile(__dirname + '/public/index.html'); 
});

http.listen(3000, () => console.log('started server on *:3000'));

And the directory structure is:目录结构是:

root 
|---index.js
|---package.json
|---public
|   |---index.html
|   |---cs
|   |   |---index.css
|   |---js
|   |   |---index.js

In the index.html in the public folder, I have the following code:public文件夹中的index.html中,我有以下代码:

<head>
    <script src="js/index.js"></script>
    <link rel="stylesheet" src="css/index.css" type="text/css" >
</head>

But no CSS is being rendered.但是没有呈现 CSS。 How can I resolve this?我该如何解决这个问题?

Try changing this:尝试改变这个:

app.use(express.static(__dirname + '/public'));

To this:对此:

app.use(express.static('public'));

Replace src attribute in link tag to href .link标签中的src属性替换为href If this doesn't work then try below solution.如果这不起作用,请尝试以下解决方案。

I'm considering your server is running on http://localhost:3000/我正在考虑您的服务器正在http://localhost:3000/上运行

So update the url in src of your index.html in public folder by appending with the base url as I did below.因此,通过附加基础index.html在公共文件夹中的 index.html 的src中更新 url,如下所示。

<head>
    <script src="http://localhost:3000/js/index.js"></script>
    <link rel="stylesheet" href="http://localhost:3000/css/index.css" type="text/css" >
</head>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM