在Express.js中使用response.sendfile时发生404错误

我有一个Express Node.js应用程序。 结构如下:

myapp +-- node_modules +-- public |-- htmls |-- myhtml.html +-- routes |-- index.js |-- app.js 

我的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')); }); 

我的routes/index.js如下:

 // Some stuff... exports.plainhtml = function(req, res) { res.sendfile('/public/htmls/' + req.params.file); }; 

我打开我的浏览器,并尝试获得以下地址: http://localhost:3000/content/myhtml.html ,我得到404错误:

快递404错误:ENOENT,stat'/public/htmls/myhtml.html'

路由完成,函数被调用…问题是当我尝试使用res.sendfile 。 我应该通过哪个地址?

该怎么办?

您的快速应用程序是在app.js

sendfilepath参数是相对path。 所以当你做res.sendfile('xxx.js') ,express会在app.js所在的目录下寻找xxx.js

如果path以斜线开始/这意味着它是文件系统中的绝对path,例如/tmp

如果您正在使用相对path,则还可以指定根path:

 res.sendfile('passwd', { root: '/etc/' }); 

看文档 。