无法加载样式表节点

时间:2016-08-30 19:40:26

标签: node.js express

我创建了基本节点/快速服务器

var express = require('express');
var app     = express();
var path    = require('path')
var port    = 8080;

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

app.get('/' , function( req , res ){
    console.log(__dirname)
    res.sendFile(path.join(__dirname,'../public/html/index.html'))
})
app.listen(port)

项目结构简单

app
  public
     html
       index.html
     styles
     javascripts
  routes
     server.js

html文件看起来很简单

<!DOCTYPE html>
<html>
<head>
     <link rel="stylesheet" href="../styles/index.css">
    <title> Hello world!</title>
</head>
<body>

</body>
</html>

但仍然抱怨

  

获取http://localhost:8080/index.css 404(未找到)

然而我的路径应该是正确的,我查找了这个问题,每个答案都是关于使用

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

所以浏览器在查找样式表时知道如何重定向。哪个对我不起作用。

有人可以帮助解决这个常见问题吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

不清楚您的项目结构是什么。在项目目录中app.js包含基本快速服务器更常见,如果您有复杂的路由,请在routes/server.js

中执行此操作

所以你可以改变你的项目结构:

app.js (main file)
public
  index.html        
  styles
    index.css
  javascripts
routes
  server.js --not needed?

如果是这种情况,请将app.js更改为:

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

//use static folder public to serve everything up
app.use(express.static('./public/'));

app.listen(port)

index.html中,加入index.css

<link rel="stylesheet" href="/styles/index.css" >
相关问题