【问题标题】:How to fetch images from node.js server's folder in URL?如何从 URL 中的 node.js 服务器文件夹中获取图像?
【发布时间】:2015-01-18 17:15:33
【问题描述】:

有人知道如何从 URL 中的 node.js 服务器文件夹中获取图像吗? 在我的文件夹结构中,我有文件夹数据,里面有带有图像的子文件夹 img。我想用 URL 访问这张图片,像这样:

http://localhost:3000/data/img/default.jpg

但是当我将它输入浏览器时,我总是会收到此错误:

页面未找到 /data/img/default.jpg 不是有效路径。

server.js:

'use strict';
/**
 * Module dependencies.
 */
var init = require('./config/init')(),
    config = require('./config/config'),
    mongoose = require('mongoose');
var express = require('express');

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */

// Bootstrap db connection
var db = mongoose.connect(config.db, function(err) {
    if (err) {
        console.error('\x1b[31m', 'Could not connect to MongoDB!');
        console.log(err);
    }
});

// Init the express application
var app = require('./config/express')(db);

// Bootstrap passport config
require('./config/passport')();

app.use(express.static('data/img'));
// Start the app by listening on <port>
app.listen(config.port);

// Expose app
exports = module.exports = app;

// Logging initialization
console.log('MEAN.JS application started on port ' + config.port);

express.js:

'use strict';

/**
 * Module dependencies.
 */
var express = require('express'),
    morgan = require('morgan'),
    bodyParser = require('body-parser'),
    session = require('express-session'),
    compress = require('compression'),
    methodOverride = require('method-override'),
    cookieParser = require('cookie-parser'),
    helmet = require('helmet'),
    passport = require('passport'),
    mongoStore = require('connect-mongo')({
        session: session
    }),
    flash = require('connect-flash'),
    config = require('./config'),
    consolidate = require('consolidate'),
    path = require('path');

module.exports = function(db) {
    // Initialize express app
    var app = express();

    // Globbing model files
    config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) {
        require(path.resolve(modelPath));
    });

    // Setting application local variables
    app.locals.title = config.app.title;
    app.locals.description = config.app.description;
    app.locals.keywords = config.app.keywords;
    app.locals.facebookAppId = config.facebook.clientID;
    app.locals.jsFiles = config.getJavaScriptAssets();
    app.locals.cssFiles = config.getCSSAssets();

    // Passing the request url to environment locals
    app.use(function(req, res, next) {
        res.locals.url = req.protocol + '://' + req.headers.host + req.url;
        next();
    });

    // Should be placed before express.static
    app.use(compress({
        filter: function(req, res) {
            return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
        },
        level: 9
    }));

    // Showing stack errors
    app.set('showStackError', true);

    // Set swig as the template engine
    app.engine('server.view.html', consolidate[config.templateEngine]);

    // Set views path and view engine
    app.set('view engine', 'server.view.html');
    app.set('views', './app/views');

    // Environment dependent middleware
    if (process.env.NODE_ENV === 'development') {
        // Enable logger (morgan)
        app.use(morgan('dev'));

        // Disable views cache
        app.set('view cache', false);
    } else if (process.env.NODE_ENV === 'production') {
        app.locals.cache = 'memory';
    }

    // Request body parsing middleware should be above methodOverride
    app.use(bodyParser.urlencoded({
        extended: true
    }));
    app.use(bodyParser.json());
    app.use(methodOverride());

    // Enable jsonp
    app.enable('jsonp callback');

    // CookieParser should be above session
    app.use(cookieParser());

    // Express MongoDB session storage
    app.use(session({
        saveUninitialized: true,
        resave: true,
        secret: config.sessionSecret,
        store: new mongoStore({
            db: db.connection.db,
            collection: config.sessionCollection
        })
    }));

    // use passport session
    app.use(passport.initialize());
    app.use(passport.session());

    // connect flash for flash messages
    app.use(flash());

    // Use helmet to secure Express headers
    app.use(helmet.xframe());
    app.use(helmet.xssFilter());
    app.use(helmet.nosniff());
    app.use(helmet.ienoopen());
    app.disable('x-powered-by');

    // Setting the app router and static folder
    app.use(express.static(path.resolve('./public')));

    // Globbing routing files
    config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
        require(path.resolve(routePath))(app);
    });

    // Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
    app.use(function(err, req, res, next) {
        // If the error object doesn't exists
        if (!err) return next();

        // Log it
        console.error(err.stack);

        // Error page
        res.status(500).render('500', {
            error: err.stack
        });
    });

    // Assume 404 since no middleware responded
    app.use(function(req, res) {
        res.status(404).render('404', {
            url: req.originalUrl,
            error: 'Not Found'
        });
    });

    return app;
};

【问题讨论】:

  • 请发布您的服务器代码。有几种方法可以做到这一点。请记住,节点不是 apache。你想做的任何事情都必须启用。您可能只是缺少访问文件的配置。
  • 其实它是由 YO mean generator 生成的。我找到了一些像这样的解决方案:var express = require('express'); var app = express.createServer(); app.use(express.static(__dirname + '/public')); app.listen(8080);但我对 node.js 很陌生,不知道如何在我的应用程序中应用它,每一个帮助都非常受欢迎
  • express.static 正是我要说的。您可以将其与现有的 app.use() 语句放在一起。我总是把这些东西放在app.configure();,但我认为没有必要。
  • 好的,所以当我在目录 data/img 中有图像时(文件夹数据与 server.js 位于同一目录中),命令将如下所示: app.use('/static', express .static('data/img'));?因为当我将此命令放入 server.js 并将此地址放入浏览器 localhost:3000/static/default.jpg 时,我得到了同样的错误

标签: javascript node.js express mean-stack mean.io


【解决方案1】:

就像您已经在下面的行中将您的 data/img 文件夹设置为静态文件夹:

app.use(express.static('data/img'));

在这种情况下,您应该使用以下 url 访问放置在上面静态文件夹中的图像:

http://localhost:3000/default.jpg

不过,我建议您使用 Node 的全局变量 __dirname 来指示静态文件夹的根目录,但这取决于您的 server.js 在文件结构中的位置。

包含下面 sn-ps 的 js 文件位于根目录中,我也有根目录中的 /data/img 文件夹,我可以使用 /image 名称检索图像。

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/data/img'));
app.listen(3500, function () {
    console.log('Express server is listening, use this url - localhost:3500/default.png');
});

看看这对你有没有帮助。如果是这样,请确保您知道使用 __dirname 全局变量名的原因。

SO1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多