综合编程

404 error when using response.sendfile in Express.js

微信扫一扫,分享到朋友圈

404 error when using response.sendfile in Express.js
0

I have an Express Node.js
application. The structure is the following:

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

My app.js
is as follows:

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

My routes/index.js
is as follows:

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

I open my browser and try to get the following address: http://localhost:3000/content/myhtml.html
and I get 404 error:

Express 404 Error: ENOENT, stat '/public/htmls/myhtml.html'

The routing is done and the function is called… the problem is when I try to use res.sendfile
. What address should I pass there???

What to do?

Problem courtesy of: Andry

Solution

Your express app is in app.js
.

The path
parameter for sendfile
is a relative path. So when you do res.sendfile('xxx.js')
, express will look for xxx.js
in the same directory that app.js
is in.

If path
starts with a slash /
it means that it’s an absolute path in the file system e.g. /tmp
.

If you are using relative paths you can also specify the root path:

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

See the docs
.

Solution courtesy of: mak

阅读原文...


Node.js Recipes

8 Step Guide to Rewrite Articles

上一篇

Delete elements from a Numpy Array by value or conditions in Python

下一篇

您也可能喜欢

评论已经被关闭。

插入图片
404 error when using response.sendfile in Express.js

长按储存图像,分享给朋友