我有一个Express Node.js应用程序.结构如下:
myapp
+-- node_modules
+-- public
|-- htmls
|-- myhtml.html
+-- routes
|-- index.js
|-- app.js
Run Code Online (Sandbox Code Playgroud)
我的app.js
情况如下:
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
// all environments
// some stuff...
app.use(express.static(path.join(__dirname, 'public')));
app.use('/public', express.static(path.join(__dirname, 'public')));
app.get('/', routes.index);
app.get('/content/:file', routes.plainhtml);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Run Code Online (Sandbox Code Playgroud)
我的routes/index.js
情况如下:
// Some stuff...
exports.plainhtml = function(req, res) {
res.sendfile('/public/htmls/' + req.params.file);
};
Run Code Online (Sandbox Code Playgroud)
我打开浏览器并尝试获取以下地址:http://localhost:3000/content/myhtml.html
我收到404错误:
Express 404错误:ENOENT,stat'/public/htmls/myhtml.html'
完成路由并调用函数......问题出在我尝试使用时res.sendfile
.我应该通过什么地址?
该怎么办?
你的快递应用程序在app.js
.
在path
用于参数sendfile
是相对路径.所以,当你这样做时res.sendfile('xxx.js')
,express将xxx.js
在同一个目录中寻找app.js
.
如果path
以斜杠开头,/
则表示它是文件系统中的绝对路径,例如/tmp
.
如果使用相对路径,还可以指定根路径:
res.sendfile('passwd', { root: '/etc/' });
Run Code Online (Sandbox Code Playgroud)
查看文档.