简体   繁体   中英

Express.js cannot access static files even after configuring express.static

I tried localhost:3000/index.html (where I put a static page), localhost:3000/javascripts/dio.js (where I put js) localhost:3000/images/dio1.jpg (where I put the images), All cannot be accessed. Why? What is wrong?

My app.js define:

var express = require('express')
var app=express()
app.bcrypt = require('bcrypt')
app.im=require('imagemagick')
app.fs=require('fs')
app.application_root = __dirname
app.path = require("path")
app.mongoose = require("mongoose")

var config=require('./config.js')(app,express)

var models = require('./models/models.js')(app.mongoose)
models.UserModel = models.UserModel
models.CommentModel = models.CommentModel
models.ItemModel = models.ItemModel

require('./routes')(app, models)

app.listen(3000);
console.log("Listening on port 3000")

Here is my config.js define:

module.exports = function(app, express, mongoose){
    var config=this

    app.configure(function (){
        app.set('views',__dirname+'/views')
        app.set('view engine','jade')
        app.set('view engine', {layout:true})

        app.use(express.bodyParser())
        app.use(express.methodOverride())
        app.use(express.cookieParser())
        app.use(express.session({secret: 'topsecret',store: new express.session.MemoryStore}))
        app.use(app.router)
        app.use(express.static(app.path.join(app.application_root+"public")))
        app.use(express.errorHandler({dumpExceptions:true,showStack:true}))
        app.use(express.bodyParser({keepExtensions: true, uploadDir:"./public/uploads"}))
    })

    /*DB part:*/
    app.mongoose.connect('mongodb://localhost/dio_database')

    return config
}

试试这种风格:

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

Instead of concatenating and joining:

 app.path.join(app.application_root+"public")

Either each part should be passed as a separate argument to path.join :

 app.path.join(app.application_root, "public")

Or, if you'd rather concatenate, __dirname won't have a trailing slash for application_root , so you'll need to add one:

 app.application_root + '/public'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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