如何从 URL 中的节点.js服务器文件夹获取图像
How to fetch images from node.js server's folder in URL?
有人知道如何从 URL 中的 node.js 服务器文件夹中获取图像吗?在我的文件夹结构中,我有文件夹数据,里面有带有图像的子文件夹 img。我想使用 URL 访问此图像,如下所示:
http://localhost:3000/data/img/default.jpg
但是当我将其输入浏览器时,我总是收到此错误:
找不到页面/data/img/default.jpg 不是有效的路径。
服务器.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);
快递.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;
};
就像您已经在下面一行中将数据/img 文件夹设置为静态文件夹一样:
app.use(express.static('data/img'));
在这种情况下,您应该使用以下 url 访问放置在上面静态文件夹中的图像:
http://localhost:3000/default.jpg
但是,我建议您使用 Node 的全局变量__dirname来指示静态文件夹的根目录,但这取决于您的服务器.js在文件结构中的位置。
包含以下代码片段的 js 文件位于根目录中,我也有来自根目录的/data/img 文件夹,我能够使用/image name 检索图像。
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 全局变量名称的原因。
二氧化硫1
相关文章:
- 使用node.js服务器中的evernote api获取note内容
- 使用JS在服务器上运行PHP脚本
- 如何将Knockout.JS与服务器已经在DOM中呈现的数据同步
- 什么's本地node.js服务器和python简单http服务器之间的区别
- renderReact/Rect Router+Node/Express.js的服务器端/同构渲染中未定义renderP
- 在HTML页面上显示node.js服务器中的数据
- 正在使用Dropzone.js删除服务器上已重命名的文件
- Angular JS文件上传到托管服务器
- node.js将字符串转换为要上传到Web服务器的文件
- 将用户制作的SVG(raphael.js)发送到服务器(php),以便通过电子邮件发送
- 如何在Angular.js中循环动态添加Fields并获取数据并将其发送到服务器
- 将服务器js文件替换为本地js进行调试
- 如何从URL隐藏内容,但仍需要在node中发送到服务器.js并表达
- 节点中的 Web 服务器.js路径中的错误
- 运行 react/redux 应用程序所需的最低服务器.js
- 节点.js我做错了哪一部分?服务器.js正在运行,但我看不到 HTML 页面
- Node.js/MongoDB:如何使用module.exports将本地主机数据库URL传递给服务器.js文件
- 如何将值从辅助函数返回给服务器.js NodeJS
- 当新行从应用程序插入到mysql表时,监听来自节点服务器js的事件
- 评估服务器js文件的危险