我是节点js express的新手。我想在位置D:\ d3 project \ index12.htm打开一个html页面。 app.js位于D:\ d3 project \ project_part1 \ project_part1 \ app.js
app.use(express.static('D:\d3 project'));
app.get('/', function (req, res) {
res.sendFile('D:/d3 project' + '/'+'index12.html');
});
var server = app.listen(3001, '0.0.0.0', function () {
console.log('Listening on port %d', server.address().port);
});
我收到此错误
TypeError: path must be absolute or specify root to res.sendFile
at ServerResponse.sendFile (D:\d3 project\project_part1\project_part1\node_modules\express\lib\response.js:403:11)
at D:\d3 project\project_part1\project_part1\app.js:10:9
at Layer.handle [as handle_request] (D:\d3 project\project_part1\project_part1\node_modules\express\lib\router\layer.js:95:5)
at next (D:\d3 project\project_part1\project_part1\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (D:\d3 project\project_part1\project_part1\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\d3 project\project_part1\project_part1\node_modules\express\lib\router\layer.js:95:5)
at D:\d3 project\project_part1\project_part1\node_modules\express\lib\router\index.js:277:22
at Function.process_params (D:\d3 project\project_part1\project_part1\node_modules\express\lib\router\index.js:330:12)
at next (D:\d3 project\project_part1\project_part1\node_modules\express\lib\router\index.js:271:10)
at SendStream.error (D:\d3 project\project_part1\project_part1\node_modules\express\node_modules\serve-static\index.js:120:7)
我想我给的是绝对路径,而不是相对路径。
解决方案: 刚刚将代码更改为
res.sendFile(path.join(__dirname + '/../../index12.html'));
并添加
var path = require('path');