我在尝试使用 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
文件夹中。
最佳答案
您没有指定绝对路径,请解决。将您的路线请求修改为
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'));
})
关于javascript - 使用 Node.js 重定向到页面时出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45499268/