简体   繁体   English

为什么我的公用文件夹没有在NodeJS应用程序中获取“ /” URL的文件?

[英]Why isn't my public folder fetching files for '/' URL in my NodeJS App?

I am trying to place static files in my public folder such as the html,css and js files but they won't fetch to the get url ('/'). 我试图将静态文件放置在我的公共文件夹中,例如html,css和js文件,但它们不会获取到获取URL('/')。 Here is my folder structure 这是我的文件夹结构

app.js
node_modules
--express
package.json
public
--style.css

My app is: 我的应用是:

var express = require('express');
var app = express();

var port = process.env.PORT || 3000;

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

app.get('/', function(req, res){
    res.send('<html><head><link href=assets/style.css type=text/css rel=stylesheet/></head><body><h1>Hello World</h1></body></html>');
});

app.get('/person/:id', function(req, res){
    res.send('<html><head></head><body><h1>Person: ' + req.params.id + '</h1></body></html>');
});

app.get('/api', function(req, res){
    res.json({ firstname: 'John', lastname: 'Doe' });
});

app.listen(port);

Style code is: 样式代码为:

 style.css:
 body {
       font-family: Arial, Helvetica, sans-sarif;   
}

Your problem is, because 你的问题是,因为

<link href=assets/style.css type=text/css rel=stylesheet/>

is equal to 等于

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

If you don't use quotes then the value is terminated by one of the following characters: " , ' , = , > , < , or ` (See W3C: 4.4. Attributes for more details). As of that your value is terminated by the > value is stylesheet/ . 如果不使用引号,则该值将以下列字符之一终止: "'=><` (请参见W3C:4.4。属性以获取更多详细信息)。通过>值是stylesheet/

Because of that the rel of your link is stylesheet/ instead of stylesheet and thats why no stylesheet is loaded. 因此, linkrel性是stylesheet/而不是stylesheet ,这就是为什么不加载样式表的原因。

So either you have to add a space between stylesheet and / : 因此,要么必须在stylesheet/之间添加一个空格:

<link href=assets/style.css type=text/css rel=stylesheet />

or you need to use quotes. 或者您需要使用引号。

您可以将“ public”重命名为“ assets”,然后使用...

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

There is syntax error in your HTML statement that links to the CSS file. HTML语句中存在链接到CSS文件的语法错误。 You forgot to enclose the values in double quotes. 您忘记将值括在双引号中。

Please use the following format: 请使用以下格式:

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

If you are using ES6 supporting Node.JS then you can use the back-ticks(``) to better format the inline HTML code like: 如果您正在使用支持Node.JS的ES6,则可以使用back-ticks(``)更好地格式化内联HTML代码,例如:

app.get('/', function(req, res){
    res.send(`
        <html>
        <head>
        <link rel="stylesheet" type="text/css" href="assets/style.css">
        </head>
        <body>
        <h1>Hello World</h1>
        </body>
        </html>`
        );
});

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

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