尝试使用Node.js显示html页面时出现一个错误。我在下面提供错误。
TypeError: path must be absolute or specify root to res.sendFile
at ServerResponse.sendFile (/opt/lampp/htdocs/heroku/FGDP/node_modules/express/lib/response.js:404:11)
at /opt/lampp/htdocs/heroku/FGDP/server.js:40:6
at Layer.handle [as handle_request] (/opt/lampp/htdocs/heroku/FGDP/node_modules/express/lib/router/layer.js:95:5)
at next (/opt/lampp/htdocs/heroku/FGDP/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/opt/lampp/htdocs/heroku/FGDP/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/opt/lampp/htdocs/heroku/FGDP/node_modules/express/lib/router/layer.js:95:5)
at /opt/lampp/htdocs/heroku/FGDP/node_modules/express/lib/router/index.js:277:22
at Function.process_params (/opt/lampp/htdocs/heroku/FGDP/node_modules/express/lib/router/index.js:330:12)
at next (/opt/lampp/htdocs/heroku/FGDP/node_modules/express/lib/router/index.js:271:10)
at Immediate.<anonymous> (/opt/lampp/htdocs/heroku/FGDP/node_modules/express-session/index.js:473:7)
我在下面提供我的代码。
var express=require('express');
var morgan = require('morgan');
var http=require('http');
var bodyParser= require('body-parser');
var methodOverride = require('method-override');
var mongo = require('mongojs');
var session = require('express-session');
var multer = require('multer')
var app=module.exports=express();
var server=http.Server(app);
var port=8989;
var admin=require('./route/route.js');
var api=require('./api/api.js');
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({ extended: false })) // parse application/x-www-form-urlencoded
app.use(bodyParser.json()) // parse application/json
app.use(methodOverride()); // simulate DELETE and PUT
app.use(session({secret: 'FGDPlexel',resave: true,saveUninitialized: true}));
app.get('/',function(req,res){
res.sendFile(__dirname + '/index.html');
})
app.get('/api/users/reset',function(req,res){
res.sendFile('views/reset.html');
})
server.listen(port);
当我输入网址http://localhost:8989/api/users/reset?id=5981b48654d471000459208e
时,我收到了上述错误。我的文件夹结构如下所示。
fgdp(root folder)
-> public
->views
->controller
server.js
我的HTML页面位于views
文件夹中。
答案 0 :(得分:1)
您没有指定绝对路径,请解决它。将您的路线请求修改为
app.get('/',function(req,res){
res.sendFile(path.join(__dirname, '/public/views', 'index.html'));
});
app.get('/api/users/reset',function(req,res){
res.sendFile(path.join(__dirname, '/public/views', 'reset.html'));
})
答案 1 :(得分:0)
控制台日志__dirname + '/index.html'
以检查index.hmtl的路径是否正确。
其次,res.sendFile('views/reset.html');
这不会起作用。它清楚地说使用绝对路径。 views/reset.html
是一条相对路径。使用path.resolve和__dirname
来获取绝对路径。