[英]Node.js Serve-static not working
I'm having some trouble with routing and serving static files. 我在路由和提供静态文件时遇到了一些麻烦。
My directory structure is like this: 我的目录结构是这样的:
app/
--app.js
—-public/
—-js/
—-main.js
—-views/
—-pages/
—-index.jade
This is how I've set up my server: 这是我设置服务器的方式:
app.js 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
But this is what happens when I visit the index: 但是,当我访问索引时会发生以下情况:
GET http://localhost:3000/public/js/main.js 404 (Not Found)
How do I set up the "serve-static" part to work? 如何设置“静态服务”部分工作? Thanks! 谢谢!
you are passing the wrong parameter to it. 您将错误的参数传递给它。
correct example for serving static files from different directory would be 从不同目录提供静态文件的正确示例是
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)
check out the docs for more options https://github.com/expressjs/serve-static 查看文档以获取更多选项https://github.com/expressjs/serve-static
I think you need to remove public from the path. 我认为您需要从路径中移除公众。
script(src="/js/main.js”)
You're telling the server static resources are served from the public folder. 您是在告诉服务器静态资源是从公用文件夹提供的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.