Node.jspath错误

在我的server.js下我有以下

app.use(express.static(__dirname + '/public')); app.get('/', function(req, res){ res.sendFile('index.html'); }); app.get('/report', function(req, res){ res.sendFile('report.html'); }); 

当我启动服务器和呈现在http:// localhost:8000我能够看到index.html,但在http:// localhost:8000 /报告我无法呈现report.html,而是我得到一个path错误path必须是绝对的或者指定res.sendFile的根

我的目录结构是

 public index.html report.html 

为什么我得到这个错误?

默认情况下,只有/被请求时, express.static()将提供index.html (请参阅文档中的参考 )。 因此,您的index.html正在由express.static()中间件提供服务,而不是由您的app.get('/', ...)路由服务。

所以,你的app.get()路线可能会有完全相同的问题。 第一个只是没有被调用,因为你的express.static()configuration已经处理该请求,并发回index.html

/report路由没有被express.static()处理,因为reportreport.html不是同一个请求。 因此,中间件不处理请求,那么你的错误configuration的app.get('/report', ...)处理程序被调用,你会得到错误的configuration错误。

这应该是你需要的一切:

 var express = require("express"); var app = express(); app.use(express.static(__dirname + '/public')); app.get('/report', function(req, res){ res.sendFile(__dirname + "/public/report.html"); }); app.listen(8080); 

或者,您可以使用path模块并使用path.join()连接这些块:

 var path = require("path"); 

然后,用这个服务文件:

 res.sendFile(path.join(__dirname, 'public', 'report.html')); 

在我自己的示例nodejs应用程序中,这些res.sendFile()选项都可以工作。

npm安装path

那么,你必须指定根path:

 var express = require('express'); var app = express(); var path = require('path'); app.use(express.static(__dirname + '/public')); app.get('/', function(req, res){ res.sendFile('index.html'); }); app.get('/report', function(req, res){ res.sendFile('report.html', { root: path.join(__dirname, './public') }); }); app.listen(8000);