Node.js Serve-static无法正常工作

时间:2016-10-19 06:22:27

标签: node.js express

我在路由和提供静态文件方面遇到了一些麻烦。

我的目录结构如下:

app/    
--app.js
—-public/
  —-js/
    —-main.js
—-views/
  —-pages/
    —-index.jade

这就是我设置服务器的方式:

app.js

var express = require('express')
var path = require('path')
var serveStatic = require('serve-static')
var publicPath = path.join(__dirname,'..','public');
var port = process.env.PORT || 3000
var app = express()

app.set('views', './views/pages')
app.set('view engine', 'jade')
app.use('/public', serveStatic(publicPath));

app.listen(port)

console.log("port is " + port)


app.get('/', function(req, res) {  
        res.render('index', {
            title: 'index',
        })
})

index.jade

doctype
html
    head
        meta(charset="utf-8")
        title index
        script(src="/public/js/main.js”)
    body
        h1=title

但是当我访问索引时会发生这种情况:

GET http://localhost:3000/public/js/main.js 404 (Not Found)

如何设置“serve-static”部分才能工作? 谢谢!

2 个答案:

答案 0 :(得分:0)

您将错误的参数传递给它。

从不同目录提供静态文件的正确示例是

This example shows a simple way to search through multiple directories. Files are look for in public-optimized/ first, then public/ second as a fallback.

var express = require('express')
var serveStatic = require('serve-static')

var app = express()

app.use(serveStatic(__dirname + '/public-optimized'))
app.use(serveStatic(__dirname + '/public'))
app.listen(3000)

查看文档了解更多选项https://github.com/expressjs/serve-static

答案 1 :(得分:0)

我认为您需要从路径中移除公众。

script(src="/js/main.js”)

您告诉服务器静态资源是从公共文件夹提供的。