提供css和javascript文件

时间:2016-08-29 19:48:45

标签: node.js express

我是节点的初学者。我正在尝试提供文件。我的项目的层次结构看起来像

应用

  modules
  node_modules
  public
    css
      index.css
    html
      index.html
    javascript
  routes
     main.js

在main.js里面

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

app.use("/styles",  express.static(path.join(__dirname + '../public/css')));
app.use("/scripts", express.static(__dirname + '../public/javascript'));

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

我想在/ route上提供文件。它工作正常,但没有加载css和javascripts - 它在browswer控制台中抛出错误

  

http://localhost:8080/css/index.css无法加载资源:   服务器响应状态为404(未找到)

设置css路径的正确方法是什么?我很难找到合适的解决方案。

谢谢!

2 个答案:

答案 0 :(得分:3)

问题在于您的路径定义。当你使用path.join时,你应该将字符串传递给它,这个方法将它们作为分隔符与平台特定的分隔符连接起来,然后规范化生成的路径。

所以你的风格路径应该是:

app.use("/styles",  express.static(path.join(__dirname, 'public', 'css')));

你的风格将来自:

http://localhost:8080/styles/index.css

因为您使用的是虚拟路径前缀(此处:/ styles)。

如果你不介意平台特定的分隔符,我。即知道您的服务器将是类似unix的环境,并且不需要虚拟路径前缀然后只需使用:

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

你的风格将来自 css dir:

http://localhost:8080/css/index.css

答案 1 :(得分:1)

因为你设置了另一条路线。将路由更改为静态文件。使用此:

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